Loading...
 
Print

SRS CSharp Coding Style Guide

10/08/2009
Mike Krüger (Original Author)
Daniel M. Best

About This Guide

This guide is an adaptation of the C# guide presented by Mike Krüger from icsharpcode.net. The guide is intended to provide a foundation for writing code that is similar and readable across developers and modules using current best practices.

File Organization

Source Files

Keep classes / files short and to the point; do not exceed 2000 lines of code if it can be helped. Divide code up; make structures and declarations clear. Put every class in a separate file and name the file with a like class name. If a class is only used as a private member to another class, then it can be kept within the parent class’s file as long as the line count is not exceeded.

Indentation

Wrapping Lines

When an expression will not fit on a single line, break it up according to these general principles:
  • Break after a comma.
  • Break after an operator.
  • Prefer higher-level breaks to lower-level breaks.
  • 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:
Preferred:
var = a * b / (c - g + f) +      4 * z; 

To be avoided:
var = a * b / (c - g +      f) + 4 * z; 

The first is preferred, because the break occurs outside the parenthesized 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 width of the tab). A good coding practice is to make the tab and space chars visible in the editor that is used.

White Spaces

An indentation standard using spaces never was achieved. Some people like 2 spaces, some prefer 4 and others die for 8, or even more spaces. It's better to use tabs. Tab characters have some advantages:
  • Everyone can set his/her own preferred indentation level.
  • It is only 1 character and not 2, 4, 8 … therefore, it will reduce typing (even with smart-indenting, you have to set the indentation manually sometimes, or take it back or whatever).
  • 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 text editor.
Here we define the Tab as the standard indentation character. Use tabs for indentation, not spaces.

Comments

Block Comments

Block comments should usually be avoided. Use of the /// comments to give C# standard descriptions is recommended. When you wish to use block comments, you should use the following style:
/* Line 1 
* Line 2 
* Line 3 
*/

As this will set off the block visually from code for the (human) reader. Alternatively, you might use this old fashioned C style for single line comments, even though it is not recommended. In case you use this style, a line break should follow the comment, as it is hard to see code proceeded by comments in the same line:
/* blah blah blah */ 

Block comments may be useful in rare cases. Refer to the TechNote "The Fine Art of Commenting" for an example. Generally, block comments are useful for commenting out large sections of code.

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. Commented out code should be commented out in the first line to enhance the visibility of commented out code.

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. Tags fall into two categories:
  • Documentation items
  • Formatting/ Referencing
The first category contains tags like <summary>, <param> or <exception>. These represent items that represent the elements of a program's API which must be documented for the program to be useful to other programmers. These tags usually have attributes such as name or cref as demonstrated in the multiline example above. These attributes are checked by the compiler, so they should be valid. The latter category governs the layout of the documentation, using tags such as <code>, <list> or <para>.Documentation can then be generated using the 'documentation' item in the #develop 'build' menu. The documentation generated is in HTMLHelp format.

For a fuller explanation of XML comments, see the Microsoft .net framework SDK documentation. For information on commenting best practice and further issues related to commenting, see the TechNote "The Fine Art of Commenting."

Declarations

Declarations Per Line

One declaration per line is recommended since it encourages commenting1. 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;

Any object that when declared has a .dispose() method exposed should be disposed of appropriately. It is often handy to use the “using” construct to declare these variables. If not used, then a try / catch / finally should be used to ensure objects are disposed of correctly.
using (OpenFileDialog openFileDialog = new OpenFileDialog()) { 
...
} 

Or
OpenFileDialog openFileDialog = null; 
try{
openFileDialog = new OpenFileDialog();
…
}
finally{
if(null != openFileDialog){openFileDialog.dispose();}
} 

Class and Interface Declarations

When coding C# classes and interfaces, the following formatting rules should be followed:
  • No space between a method name and the parenthesis " (" starting its parameter list.
  • The opening brace "{" appears in the next line after the declaration statement
  • The closing brace "}" starts a line by itself indented to match its corresponding opening brace.
For example:
Class MySample : MyClass, IMyInterface
{
int myInt;
public MySample(int myInt)
{
this.myInt = myInt;
}
void Inc()
{
++myInt;
}
void EmptyMethod()
{
}
} 

For a brace placement example, look at section 10.1.

Statements

Simple

Each line should contain only one statement.

Return

A return statement should not use outer most parentheses.

Bad practice:
return (n * (n + 1) / 2); 

Good practice:
return n * (n + 1) / 2; 

Conditional

if, if-else and if else-if else
Should keep the else and else if notation on the same line as the closing bracket of the initial if statement.
if (condition) {
DoSomething();
...
}
if (condition) {
DoSomething();
...
} else {
DoSomethingOther();
...
}
if (condition) {
DoSomething();
...
} else if (condition) {
DoSomethingOther();
...
} else {
DoSomethingOtherAgain();
...
} 

Switch
A switch statement should be of following form:
switch (condition) {
case A:
...
break;
case B:
...
break;
default:
...
break;
} 

Looping

for / foreach
A for statement should have following form:
for (int i = 0; i < 5; ++i) {
...
} 

or single lined:
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
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); 

try / catch / finally
It is considered bad form to catch the base type “Exception” when writing try catch blocks. If an particular exception is possible, catch it and handle it appropriately. An exception to this is when logging and re-throwing. A try-catch statement should follow this form:
try {
...
} catch (ArgumentException e) {}

or
try {
...
} catch (ArgumentException e) {
...
}

or
try {
...
} catch (ArgumentException e) {
...
} finally {
...
} 

White Space

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:
  • Logical sections of a source file
  • Class and interface definitions (try one class/interface per file to prevent this case)
One blank line should always be used between:
  • Methods
  • Properties
  • Local variables in a method and its first statement
  • 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

There should be a single space after a comma or a semicolon.

Good practice:
TestMethod(a, b, c); 

Bad practice
TestMethod(a,b,c)

or
TestMethod( a, b, c );

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

Good practice:
a = b;
for (int i = 0; i < 10; ++i){} 

Bad practice:
a=b; 
for (int i=0; i<10; ++i){}
for(int i=0;i<10;++i){} 

Tab Formatting

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.

Naming Conventions

Capitalization Style

Pascal
This convention capitalizes the first character of each word (as in TestCounter).

Camel
This convention capitalizes the first character of each word except the first one-- e.g., testCounter.

Uppercase
Only use all uppercase 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.

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
  • Class names must be nouns or noun phrases.
  • UsePascal Casing see 8.1.1
  • Do not use any class prefix
Interface Naming
  • Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
  • Use Pascal Casing (see 8.1.1)
  • Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)
Enum
  • 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.
Read Only and Constant
  • Name static fields with nouns, noun phrases or abbreviations for nouns
  • Use Pascal Casing (see 8.1.1)
__Parameter / Non-Constant
  • 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 (see 8.1.2)
Variables
  • Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops. (see 10.2 for an example on more intelligent naming for global counters etc.)
  • Use Camel Casing (see 8.1.2)
Methods
  • Name methods with verbs or verb phrases.
  • Use Pascal Casing (see 8.1.2)
Property Names
  • Name properties using nouns or noun phrases
  • Use Pascal Casing (see 8.1.2)
  • Consider naming a property with the same name as its type
Event Names
  • Use two parameters named sender and e
  • Use Pascal Casing (see 8.1.1)
  • 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.
Summary
TypeClassNotes
Class/StructPascal Casing
InterfacePascal CasingStarts with I
Enum valuesPascal Casing
EventsPascal Casing
Exception classPascal CasingEnd with Exception
Public FieldsPascal Casing
MethodsPascal Casing
NamespacePascal Casing
PropertyPascal Casing
Protected/private fieldsCamel Casing
ParametersCamel Casing


Programming Practices

Visibility

Do not make any instance or class variable public - make them private. For private members, it's preferable to not use “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.

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 hard-coded into your code in 50 lines scattered throughout 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...
} 


Page last modified on Friday, May 27, 2011

Print