Vous êtes sur la page 1sur 22

C# Coding Standards

Contents
1.

............................................................................................................................................................. 3

1.1

1.2

1.3

1.4

2.

............................................................................................................................................... 4

2.1

2.2

2.3

3.
3.1

................................................................................................................................................... 5

4.

C# Golden Rules ........................................................................................................................................ 7

5.

............................................................................................................................................................. 8

5.1

Class Layout

5.2

Indicating Scope

5.3

Indentation & Braces

5.4

Long lines of code

6.

Commenting ............................................................................................................................................. 11

6.1

Intellisense Comments

11

6.2

End-Of-Line Comments

11

6.3

Single Line Comments

11

6.4

// TODO: Comments

11

6.5

C-Style Comments

11

7.
7.1

Capitalization & Naming ......................................................................................................................... 12


Capitalization

12

7.2

8.

Naming

12

Programming ........................................................................................................................................... 13

8.1

Namespaces

13

8.2

Classes & Structures

13

8.3

Interfaces

13

8.4

Constants

14

8.5

Enumerations

14

8.6

Variables, Fields & Parameters

15

8.7

Properties

15

8.8

Methods

16

8.9

Event Handlers

16

8.10

Error Handling

16

8.11

18

Appendix A. ....................................................................................................................................... 21
A.1 :

21

A.2 :

21

A.3

21

A.4

21

1.
1.1
Coding Style

1.2
C# Component LibraryWeb ServiceWeb Site Client
Application

1.3
Visual Studio

1.4

2.
2.1
Microsoft .Net Framework 4.5
Microsoft Visual Studio 2012
Microsoft SQL Server 2012
C#

2.2

ASP.NET MVC 4
Windows Forms Application
:Windows Service

2.3

(1)

(2) (Codename)
[Bad]
JellySeaFrontEnd
JellySeaBackEnd
[Good]
Jellysea
CandyRain
FrontEnd

3.
3.1
N-Tier

IIS Cache
APIStored Procedure API

Interface
Backend WCF, Web Service, REST Service, DLL

Controller Frontend
Controller
Frondend Backend

4. C# Golden Rules

o
o
o (Test Driven Development)

o
o // TODO:

o (const) (Enum)
o while foreach
o StringBuilder

o IDisposable using try-finally

o Log UI MessageBox
o

5.
5.1 Class Layout
#region

Example:
// Class layout based on accessibility
class Purchasing
{
#region Main
#region Public
#region Internal
#region Protected
#region Private
#region Extern
#region Designer Generated Code
}

Guidelines:
o layout
o regions
o Code Gen regions

5.2 Indicating Scope

Example:
string connectionString = DataAccess.DefaultConnectionString;
float amount = this.CurrentAmount;
this.discountedAmount = this.CalculateDiscountedAmount(amount,
this.PurchaseMethod);

Guidelines:
o keyword this
o

5.3 Indentation & Braces

Example:

float CalculateDiscountedAmount(float amount, PurchaseMethod purchaseMethod)


{
// Calculate the discount based on the purchase method
float discount = 0.0f;
switch( purchaseMethod )
{
case PurchaseMethod.Cash:
// Calculate the cash discount
discount = this.CalculateCashDiscount( amount );
Trace.Writeline( Cash discount of {0} applied., discount );
break;
case PurchaseMethod.CreditCard:
// Calculate the credit card discount
discount = this.CalculateCreditCardDiscount( amount );
Trace.WriteLine( Credit card discount of {0} applied., discount );
break;
default:
// No discount applied for other purchase methods
Trace.WriteLine( No discount applied. );
break;
}
// Compute the discounted amount, making sure not to give money away
float discountedAmount = amount discount;
if( discountedAmount < 0.0f )
{
discountedAmount = 0.0f;
}
LogManager.Publish( discountedAmount.ToString() );
// Return the discounted amount
return discountedAmount;
}

[]
( properties ) getter setter
Example:
public int ID { get; set; }

Object Initializers 80
Example:
Customer c = new Customer() { Name = "Bart", City = "Ghent", Age = 23 };

5.4 Long lines of code


80


(struct)
Example:
string Win32FunctionWrapper(
int
arg1,
string arg2,
bool
arg3 )
{
// Perform a PInvoke call to a win32 function,
// providing default values for obscure parameters,
// to hide the complexity from the caller
if( Win32.InternalSystemCall(
null,
arg1, arg2,
Win32.GlobalExceptionHandler,
0, arg3,
null )
{
return Win32 system call succeeded.;
}
else
{
return Win32 system call failed.;
}
}

Guidelines:

o
Visual Studio Intellisense
o

10

6.

Commenting
6.1 Intellisense Comments
/// public, internal,

protected

6.2 End-Of-Line Comments

End-of-Line comments
Example:
private string name = string.Empty; // Name of control (defaults to blank)

6.3 Single Line Comments

End-of-Line Comment

Example:
// Compute total price including all taxes
float stateSalesTax = this.CalculateStateSalesTax( amount, Customer.State );
float citySalesTax = this.CalculateCitySalesTax( amount, Customer.City );
float localSalesTax = this.CalculateLocalSalesTax( amount, Customer.Zipcode );
float totalPrice
= amount + stateSalesTax + citySalesTax + localSalesTax;
Console.WriteLine( Total Price: {0}, totalPrice );

6.4 // TODO: Comments


// TODO:

6.5 C-Style Comments


/**/

11

7. Capitalization & Naming


7.1 Capitalization
Naming Guidelines
Examples:
Identifier Type

Capitalization Style

Example(s)

Upper

ID, REF

(namespaces)

Pascal

AppDomain, System.IO

(Classes & Structs)

Pascal

AppView

(Constants & Enums)

Pascal

TextStyles

(Interfaces)

Pascal

IEditableObject

(Enum values)

Pascal

TextStyles.BoldText

(Property)

Pascal

BackColor

(Variables, and Attributes)

Pascal (public)
Camel (private, protected, local)

WindowSize
windowWidth, windowHeight

(Methods)

Pascal (public, private, protected)


Camel (parameters)

ToString()
SetFilter(string filterValue)

(Local Variables)

Camel

recordCount

Guidelines:

o Pascal casing public namespaces,


classes, structures, properties, methods.
o Camel casing private protected
method parameters passed to methods method
o Upper casing

7.2 Naming
Appendix A.

12

8. Programming
8.1 Namespaces

CompanyName.ProjectOrDomainName.PackageName.SubsystemName.
Examples:
Microsoft.Data.DataAccess
Microsoft.Logging.Listeners

Guidelines:

o Pascal casing
o cs

8.2 Classes & Structures


+

Examples:
public class MainForm : Form
public class CustomerCollection : CollectionBase

Guidelines:
o Pascal casing
o
(Single Responsibility Principle)
o (Interface Segregation Principle)
o ///
o
o
o cs partial class

cs

8.3 Interfaces
+

13

Examples:
Icomponent
Iformattable
ITaxableProduct

Guidelines:
o I.
o Pascal casing
o cs
o

8.4 Constants
+ +
Example:
public const int DefaultValue = 25;
public static readonly string DefaultDatabaseName = "Membership";

Guidelines:
o Pascal casing

o static readonly const

8.5 Enumerations
+ +
Example:
/// <summary>
/// Enumerates the ways a customer may purchase goods.
/// </summary>
[Flags]
public enum PurchaseMethod
{
All
,
None
,
Cash
,
Check
,
CreditCard
,
DebitCard
,
Voucher
}

Guidelines:
o Pascal casing
o

14

o
o [Flags]( attribute )
o cs

8.6 Variables, Fields & Parameters


+ +
Examples:
int lowestCommonDenominator = 10;
float firstRedBallPrice = 25.0f;

Guidelines:
o Camel casing
o
o
o
o ( idx ) F33
index i, j, k
foreach for
o isOpen isNotOpen

8.7 Properties
+ +
Examples:
public string TotalPrice
{
get
{
return this.totalPrice;
}
set
{
// Set value and fire changed event if new value is different
if( !object.Equals( value, this.totalPrice )
{
this.totalPrice = value;
this.OnTotalPriceChanged();
}
}
}

Guidelines:

o Appendix A.
GenXinShuXin

15

8.8 Methods
+ +
Example:
private Ball FindRedCansByPrice(
float price,
int canListToPopulate,
int numberOfCansFound )

Guidelines:
o
Examples
public CustomizedOutputObject Execute(CustomizedInputObject object)


Strategy Method

o int string
o Method Parameter outref params
o
o
o 32

o
o #region #region

8.9 Event Handlers


_
Example:
private HelpButton_Click( object sender, EventArgs e )

8.10 Error Handling


catch
Guidelines:

o try-catch
o

16


o Catch(Exception) try
Exception Excepion
MSDN Intellisense try-catch

ArgumentException (and ArgumentNull, ArgumentOutOfRange,


IndexOutOfRange):

InvalidOperationException:

NotSupportedException:

NotImplementedException:

o Exception Exception
o
[Bad and Wrong]
catch (Exception ex)
{
LogManager.Publish(ex);
throw ex;
// INCORRECT we lose the call stack of the exception
}

17


catch (Exception ex)
{
LogManager.Publish(ex);
throw;
// INCORRECT we lose the call stack of the exception
}

throw;
throw ex

throw;

8.11
o (string, int, booletc).Net Framework (String,
Int32, Boolean)
o var
var var1 = "This is clearly a string.";
var var2 = 27;
var var3 = Convert.ToInt32(Console.ReadLine());

int var4 = ExampleClass.ResultSoFar();

==! = Equals

Equals(comparedString, StringComparison.CurrentCultureIgnoreCase)

Equals(comparedString, StringComparison.CurrentCulture)
[]
Equals

TryParse

Convert

To<<Type>>

Parse Exception

Unboxing/boxing

To<<Type>> API

18

string.Empty

string.IsNullOrEmpty()

string.Format()+
StringBuilder

Object Initializers Collection Initializers

[Example]
Object Initializers
Customer c = new Customer() { Name = "Bart", City = "Ghent", Age = 23 };

Collection Initializers
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

bool true/false

[Example]
[bad]
while (condition == false)
while (condition != true)
while (((condition == true) == true) == true)
[Good]
while (condition) // OK

DataTable DataSet

Linq Extension Method

IQueryable<>

(?: ) ( ?? ) if-else-if

if-else-if switch-case

else

private void CheckData()


{
string PersonalIDPattern = @"[A-Z]{1}[0-9]{9}";
string EnglishNamePattern = @"\p{L}+\s\p{L}+";
if (Regex.IsMatch(txtPersonalID.Text, PersonalIDPattern)
&& (!string.IsNullOrEmpty(txtChineseName.Text))
&& Regex.IsMatch(txtEnglishName.Text, EnglishNamePattern))
{
// Do Case 1;
}
return;
}

19

private void CheckData()


{
if (IsMatchPattern())
{
// Do Case 1;
}
}
private bool IsMatchPattern()
{
string PersonalIDPattern = @"[A-Z]{1}[0-9]{9}";
string EnglishNamePattern = @"\p{L}+\s\p{L}+";
return Regex.IsMatch(txtPersonalID.Text, PersonalIDPattern)
&& (!string.IsNullOrEmpty(txtChineseName.Text))
&& Regex.IsMatch(txtEnglishName.Text, EnglishNamePattern);
}

20

switch-case

switch case Enum

case break;

case default:

Appendix A.
A.1 :
Old/New
Source/Destination
Source/Target
First/Next/Current/Previous/Last
Min/Max

A.2 :
Allow (Allows)
Can
Contains
Has
Is
Use (Uses)

A.3
Add/Remove

Open/Close

Insert/Delete

Create/Destroy

Increment/Decrement

Acquire/Release

Lock/Unlock

Up/Down

Begin/End

Show/Hide

Fetch/Store

Start/Stop

To/From (Convert implied)

A.4
Avg

Limit

Count

Ref

Entry

Sum

Index

Total

Note: Num Index Count Temp


SwapValue TempValue

21

Vous aimerez peut-être aussi