C# Coding Style Guide

// When in Rome, do as the Romans do.

// Rome wasn’t built in a day.

Download PDF here

Layout Conventions & File Organization

Use Resharper for Visual Studio to assist in code inspections, automated code refactorings, blazing fast navigation, and coding assistance. It automatically readys the C# Coding style in your project and gives you real time suggestion andd tips to improve on it.

Good layout uses formatting to emphasize the structure of your code and to make the code easier to read.

  • Use the default Code Editor Settings (smart indenting, four-character indents, tabs saved as spaces).
  • Write only one statement per line.
  • Write only one declaration per line.
  • If continuation lines are not indented automatically, indent them one tab stop (four spaces).
  • Add at least one blank line between method definitions and property definitions.
  • Use parentheses to make clauses in an expression apparent, as shown in the following code.

if ((val1 > val2) && (val1 > val3))

{

// Take appropriate action.

}

C Sourcefiles

  • Keep your classes/files short, don’t exceed 2000 LOC, divide your code up, make structures clearer. Put every class in a separate file and name the file like the class name (with .cs as extension of course). This convention makes things much easier.
  • Create a directory for every namespace. (For MyProject.TestSuite.TestTier use MyProject/
  • TestSuite/TestTier as the path, do not use the namespace name with dots.) This makes it easier to map namespaces to the directory layout.

Directory Layout

  • Create a directory for every namespace. (For MyProject.TestSuite.TestTier use MyProject/
  • TestSuite/TestTier as the path, do not use the namespace name with dots.) This makes it easier to map namespaces to the directory layout.

 

Commenting Conventions

  • Place the comment on a separate line, not at the end of a line of code.
  • Begin comment text with an uppercase letter.
  • End comment text with a period.
  • Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.
  • Do not create formatted blocks of asterisks around comments.
  • Block comments should usually be avoided. For descriptions use of the /// comments to give C ♯ standard descriptions is recommended. When you wish to use block comments you should use the following style :

// The following declaration creates a query. It does not run // the query.

 

/* Line 1

* Line 2

* Line 2

*/

 

  • Single Line Comments: You should use the // comment style to “comment out” code (SharpDevelop has a key for it, Alt+/) . It may be used for commenting sections of code too. Single line comments must be indented to the indent level when they are used for code documentation. A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.
  • Documentation Comments: In the .net framework, Microsoft has introduced a documentation generation system based on XML comments. These comments are formally single line C♯ comments containing XML tags. They follow this pattern for single line comments:

/// <summary>

/// This class…

/// </summary>

 

Multiline XML comments follow this pattern:

/// <exception cref=”BogusException”>

/// This exception gets thrown as soon as a

/// Bogus flag gets set.

/// </exception>

 

All lines must be preceded by three slashes to be accepted as XML comment lines.

 

Naming Conventions

 

Capitalization Styles

  • Pascal Casing: This convention capitalizes the first character of each word (as in TestCounter).
  • Camel Casing: This convention capitalizes the first character of each word except the first one. E.g. testCounter.
  • Upper case: Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal Casing instead. For Example:

public class Math

{

public const PI = …

public const E = …

public const feigenBaumNumber = …

}

 

Naming Guidelines

  • Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice. Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early Windows programming, but now is obsolete or at least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.
  • And remember: a good variable name describes the semantic not the type.
  • An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button should be postfixed with their type name without abbreviations. For example:

System.Windows.Forms.Button cancelButton;

System.Windows.Forms.TextBox nameTextBox;

 

Class Naming Guidelines

  • Class names must be nouns or noun phrases.
  • Use Pascal Casing
  • Do not use any class prefix

Interface Naming Guidelines

  • Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
  • Use Pascal Casing
  • Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)

Enum Naming Guidelines

  • Use Pascal Casing for enum value names and enum type names
  • Don’t prefix (or suffix) a enum type or enum values
  • Use singular names for enums
  • Use plural name for bit fields.
  • Name static fields with nouns, noun phrases or abbreviations for nouns

Parameter/non const field Names

  • Do use descriptive names, which should be enough to determine the variable meaning and it’s type. But prefer a name that’s based on the parameter’s meaning.
  • Use Camel Casing

Variable Names

  • Counting variables are preferably called i, j, k, l, m, n when used in ‘trivial’ counting loops.
  • Use Camel Casing

Method Names

  • Name methods with verbs or verb phrases.
  • Use Pascal Casing

Property Names

  • Name properties using nouns or noun phrases
  • Use Pascal Casing
  • Consider naming a property with the same name as it’s type

Event Names

  • Name event handlers with the EventHandler suffix.
  • Use two parameters named sender and e
  • Use Pascal Casing
  • Name event argument classes with the EventArgs suffix.
  • Name event names that have a concept of pre and post using the present and past tense.
  • Consider naming events using a verb.

 

Capitalization summary

Type CaseNotes
Class / StructPascal Casing
InterfacePascal Casing Starts with I
Enum valuesPascal Casing
Enum typePascal Casing
EventsPascal Casing
Exception classPascal Casing End with Exception
public FieldsPascal Casing
MethodsPascal Casing
NamespacePascal Casing
PropertyPascal Casing
Protected/private FieldsCamel Casing
ParametersCamel Casing

 

Visibility

  • Do not make any instance or class variable public, make them private. For private members prefer not using “private” as modifier just do write nothing. Private is the default case and every C ♯ programmer should be aware of it.
  • Use properties instead. You may use public static fields (or const) as an exception to this rule, but it should not be the rule.

No ‘magic’ Numbers

  • Don’t use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded into your code in 50 lines scattered troughout your 25000 LOC) is error-prone and unproductive. Instead declare a const variable which contains the number :

public class MyMath

{

public const double PI = 3.14159…

}

 

Indentation

 

Wrapping Lines

  • When an expression will not fit on a single line, break it up according to these general principles:
  1. Break after a comma.
  2. Break after an operator.
  3. Prefer higher-level breaks to lower-level breaks.
  4. Align the new line with the beginning of the expression at the same level on the previous line
  • Example of breaking up method calls:

longMethodCall(expr1, expr2, expr3, expr4, expr5);

 

  • Examples of breaking an arithmetic expression:

PREFER:

var = a * b / (c – g + f) +  4 * z;

 

BAD STYLE – AVOID:

var = a * b / (c – g + f) + 4 * z;

 

  • The first is preferred, since the break occurs outside the paranthesized expression (higher level rule). Note that you indent with tabs to the indentation level and then with spaces to the breaking position in our example this would be:

> var = a * b / (c – g + f) +

> ……4 * z;

 

Where ‘>’ are tab chars and ‘.’ are spaces. (the spaces after the tab char are the indent with of the tab). A good coding practice is to make the tab and space chars visible in the editor which is used.

 

White Spaces

  • An indentation standard using spaces never was achieved. Some people like 2 spaces, some prefer 4 and other’s die for 8, or even more spaces. Better use tabs. Tab characters have some advantages:
  1. Everyone can set their own preferred indentation level
  2. It is only 1 character and not 2, 4, 8 … therefore it will reduce typing (even with smartindenting you have to set the indentation manually sometimes, or take it back or whatever)
  3. If you want to increase the indentation (or decrease), mark one block and increase the indent level with Tab with Shift-Tab you decrease the indentation. This is true for almost any texteditor.
  • Here, we define the Tab as the standard indentation character.
  • Don’t use spaces for indentation – use tabs!

Blank Lines

  • Blank lines improve readability. They set off blocks of code which are in themselves logically related.
  • Two blank lines should always be used between:
  1. Logical sections of a source file
  2. Class and interface definitions (try one class/interface per file to prevent this case)
  3. One blank line should always be used between:
    1. Methods
    2. Properties
    3. Local variables in a method and its first statement
    4. Logical sections inside a method to improve readability

Note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier.

Inter-term spacing

  • There should be a single space after a comma or a semicolon, for example:

TestMethod(a, b, c); don’t use : TestMethod(a,b,c)

or

TestMethod( a, b, c );

 

  • Single spaces surround operators (except unary operators like increment or logical not), example:

a = b; // don’t use a=b;

for (int i = 0; i < 10; ++i) // don’t use for (int i=0; i<10; ++i)

// or

// for(int i=0;i<10;++i)

 

  • A logical block of lines should be formatted as a table:

string name = “Mr. Ed”;

int myValue = 5;

Test aTest = Test.TestYou;

 

  • Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.

 

Declarations

 

Number of Declarations per Line

  • One declaration per line is recommended since it encourages commenting. In other words,

int level; // indentation level

int size; // size of table

 

  • Do not put more than one variable or variables of different types on the same line when declaring them. Example:

int a, b; //What is ‘a’? What does ‘b’ stand for?

 

The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.

Initialization

  • Try to initialize local variables as soon as they are declared. For example:

string name = myObject.Name;

or

int val = time.Hours;

 

Note: If you initialize a dialog try to use the using statement:

using (OpenFileDialog openFileDialog = new OpenFileDialog()) {

}

 

Class and Interface Declarations

  • When coding C♯ classes and interfaces, the following formatting rules should be followed:
  1. No space between a method name and the parenthesis “(” starting its parameter list.
  2. The opening brace “{” appears in the next line after the declaration statement.
  3. The closing brace ” }” starts a line by itself indented to match its corresponding opening brace. For example :

class MySample : MyClass, IMyInterface

{

int myInt;

Of course, using self-explanatory variable names such as indentLevel make these comments obsolete.

public MySample(int myInt)

{

this.myInt = myInt ;

}

 

void Inc()

{

++myInt;

}

 

void EmptyMethod()

{

}

}

 

Language Guidelines

 

Simple Statements

  • Each line should contain only one statement.

Return Statements

  • A return statement should not use outer most parentheses.

Don’t use : return (n * (n + 1) / 2);

use : return n * (n + 1) / 2;

 

String Data Type

  • Use the+ operator to concatenate short strings, as shown in the following code.

string displayName = nameList[n].LastName + “, ” + nameList[n].FirstName;

 

  • To append strings in loops, especially when you are working with large amounts of text, use aStringBuilder

var phrase = “lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala”;

var manyPhrases = new StringBuilder();

for (var i = 0; i < 10000; i++)

{

manyPhrases.Append(phrase);

}

//Console.WriteLine(“tra” + manyPhrases);

 

Implicitly Typed Local Variables

  • Useimplicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

// When the type of a variable is clear from the context, use var

// in the declaration.

var var1 = “This is clearly a string.”;

var var2 = 27;

var var3 = Convert.ToInt32(Console.ReadLine());

 

  • Do not usevar when the type is not apparent from the right side of the assignment.

// When the type of a variable is not clear from the context, use an

// explicit type.

int var4 = ExampleClass.ResultSoFar();

 

  • Do not rely on the variable name to specify the type of the variable. It might not be correct.

// Naming the following variable inputInt is misleading.

// It is a string.

var inputInt = Console.ReadLine();

Console.WriteLine(inputInt);

 

  • Avoid the use ofvar in place of dynamic.
  • Use implicit typing to determine the type of the loop variable infor and foreach

The following example uses implicit typing in a for statement.

var syllable = “ha”;var laugh = “”;for (var i = 0; i < 10; i++){    laugh += syllable;    Console.WriteLine(laugh);}

The following example uses implicit typing in a foreach statement.

foreach (var ch in laugh){    if (ch == ‘h’)        Console.Write(“H”);    else        Console.Write(ch);}Console.WriteLine();

Unsigned Data Type

  • In general, useint rather than unsigned types. The use of int is common throughout C#, and it is easier to interact with other libraries when you use int.
  • Use the concise syntax when you initialize arrays on the declaration line.
  • Use the concise syntax to create instances of a delegate type.

Arrays

// Preferred syntax. Note that you cannot use var here instead of string[]. string[] vowels1 = { “a”, “e”, “i”, “o”, “u” };  // If you use explicit instantiation, you can use var. var vowels2 = new string[] { “a”, “e”, “i”, “o”, “u” }; // If you specify an array size, you must initialize the elements one at a time. var vowels3 = new string[5];vowels3[0] = “a”;vowels3[1] = “e”;// And so on.

Delegates

// First, in class Program, define the delegate type and a method that   // has a matching signature.  // Define the type. public delegate void Del(string message); // Define a method that has a matching signature. public static void DelMethod(string str){    Console.WriteLine(“DelMethod argument: {0}”, str);} // In the Main method, create an instance of Del.  // Preferred: Create an instance of Del by using condensed syntax.Del exampleDel2 = DelMethod; // The following declaration uses the full syntax.Del exampleDel1 = new Del(DelMethod);

If, if-else, if else-if else Statements

if, if-else and if else-if else statements should look like this:

if (condition) {

DoSomething();

}

if (condition) {

DoSomething();

} else {

DoSomethingOther();

}

if (condition) {

DoSomething();

} else if (condition) {

DoSomethingOther();

} else {

DoSomethingOtherAgain();

}

 

Try-catch Statements

A try-catch statement should follow this form:

try {

} catch (Exception) {}

or

try {

} catch (Exception e) {

}

or

try {

} catch (Exception e) {

} finally {

}

 

try-catch and using Statements in Exception Handling

  • Use atry-catch statement for most exception handling.
  • Simplify your code by using the C#using statement. If you have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using statement instead.

static string GetValueFromArray(string[] array, int index){    try    {        return array[index];    }    catch (System.IndexOutOfRangeException ex)    {        Console.WriteLine(“Index is out of range: {0}”, index);        throw;    }}// This try-finally statement only calls Dispose in the finally block.Font font1 = new Font(“Arial”, 10.0f);try{    byte charset = font1.GdiCharSet;}finally{    if (font1 != null)    {        ((IDisposable)font1).Dispose();    }}  // You can do the same thing with a using statement. using (Font font2 = new Font(“Arial”, 10.0f)){    byte charset = font2.GdiCharSet;}

 

For / Foreach Statements

A for statement shoud have following form :

for (int i = 0; i < 5; ++i) {

}

 

or single lined (consider using a while statement instead) :

for (initialization; condition; update) ;

A foreach should look like :

foreach (int i in IntList) {

}

 

Note: Generally use brackets even if there is only one statement in the loop.

 

While/do-while Statements

A while statement should be written as follows:

while (condition) {

}

 

An empty while should have the following form:

while (condition) ;

A do-while statement should have the following form:

do {

} while (condition);

 

Switch Statements

A switch statement should be of following form:

switch (condition) {

case A:

break;

case B:

break;

default:

break;

}

 

&& and || Operators

  • To avoid exceptions and increase performance by skipping unnecessary comparisons, use&& instead of & and || instead of | when you perform comparisons, as shown in the following example.
  • Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.

Console.Write(“Enter a dividend: “);var dividend = Convert.ToInt32(Console.ReadLine()); Console.Write(“Enter a divisor: “);var divisor = Convert.ToInt32(Console.ReadLine()); // If the divisor is 0, the second clause in the following condition // causes a run-time error. The && operator short circuits when the // first expression is false. That is, it does not evaluate the // second expression. The & operator evaluates both, and causes  // a run-time error when divisor is 0. if ((divisor != 0) && (dividend / divisor > 0)){    Console.WriteLine(“Quotient: {0}”, dividend / divisor);}else{    Console.WriteLine(“Attempted division by 0 ends up here.”);}

New Operator

var instance1 = new ExampleClass();

The previous line is equivalent to the following declaration.

ExampleClass instance2 = new ExampleClass();

  • Use object initializers to simplify object creation.
  • If you are defining an event handler that you do not need to remove later, use a lambda expression.
  • Callstatic members by using the class name: StaticMember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.
  • Use meaningful names for query variables. The following example usesseattleCustomers for customers who are located in Seattle.
  • Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.
  • Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them asNameand ID in the result, rename them to clarify that Name is the name of a customer, and ID is the ID of a distributor.
  • Use implicit typing in the declaration of query variables and range variables.
  • Align query clauses under thefrom clause, as shown in the previous examples.
  • Usewhere clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.
  • Use multiplefrom clauses instead of a join clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.

// Object initializer. var instance3 = new ExampleClass { Name = “Desktop”, ID = 37414,     Location = “Redmond”, Age = 2.3 }; // Default constructor and assignment statements. var instance4 = new ExampleClass();instance4.Name = “Desktop”;instance4.ID = 37414;instance4.Location = “Redmond”;instance4.Age = 2.3;

Event Handling

public Form2(){    // You can use a lambda expression to define an event handler.     this.Click += (s, e) =>        {            MessageBox.Show(                ((MouseEventArgs)e).Location.ToString());        };} // Using a lambda expression shortens the following traditional definition. public Form1(){    this.Click += new EventHandler(Form1_Click);} void Form1_Click(object sender, EventArgs e){    MessageBox.Show(((MouseEventArgs)e).Location.ToString());}

 

Usings

Organize usings in alphabetical order, in 3 groups, .Net runtime, 3rd party libraries, this project. Each group sorted alphabetically and separated with a new line. Example:

using System.a
using System.b

using Log4Net.A
using Log4Net.B
using NUnit.A

usingGoogle.Api

 

Blocks

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someExpression)
{
DoSomething();
}
else
{
DoSomethingElse();
}

“case” statements should be indented from the switch statement like this:

switch (someExpression)
{

case 0:
DoSomething();
break;

case 1:
DoSomethingElse();
break;

case 2:
// With a variable.
{
int n = 1;
DoAnotherThing(n);
}
break;

case 3:
// Without a variable.
DoAnotherThing(n);
DoAnotherThing(n);
break;
}

 

Braces

Braces are never considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability:

if (someExpression)
{
return true;
}

 

Properties

When no logic is required automatic properties are preferred. These should be on one line. e.g.

public string Name { get; set; }
publicstringEmailAddress{get;privateset;}

If logic or logging is required use the following form

private string name;

public string Name
{
get
{
// multiple line logic
name += ” “;
return name;
}
set { this.name = value; }
}

private string emailAddress;

public string EmailAddress
{
get { return emailAddress; } // Single line logic.
set
{
// multiple line logic
this.emailAddress = value;
DoSomething();
}
}

 

Attributes

Attributes should never have () unless an argument is given:

[Test]
public void SomethingTest() { … }

[SomeAttribute(true)]
publicvoidSomeMethod(){…}

 

Usage of the this keyword

The this keyword should only be used in front of member variables:

SomeMethodCall();
this.someMember=2;

The this keyword should be ommited where it is legal to, unless it is likely to cause confusion

public class Foo
private string bar;
private int calculated;

public string Bar { get { return bar; } } // Not this.bar .

public Foo(string bar)
{
this.bar = bar; // this keyword is required.
this.calculated = bar.length; // this keyword is acceptable.
}

 

References:

http://www.microsoft.com/en-us/download/confirmation.aspx?id=7029

http://msdn.microsoft.com/en-us/library/ff926074.aspx

http://www.icsharpcode.net/technotes/sharpdevelopcodingstyle03.pdf

http://msdn.microsoft.com/en-us/library/ms229042.aspx

http://www.danrigsby.com/Files/csharpcodingstandards.doc

http://submain.com/products/guidelines.aspx

http://weblogs.asp.net/lhunt/archive/2004/08/17/CSharpCodingStandardsv113.aspx

http://www.dotnetspider.com/tutorials/BestPractices.aspx

http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx

http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf

https://code.google.com/p/google-api-dotnet-client/wiki/CodingStandards

Print Friendly, PDF & Email

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *