C# Coding Style Guide
C# Coding Style Guide
This document may be read as a guide to writing robust and reliable programs. It focuses
on programs written in C#, but many of the rules and principles are useful even if you
write in another programming language.
2. File Organization
a. C# Source files
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.
b. Directory Layout
3. Indentation
a. Wrapping Lines
When an expression will not fit on a single line, break it up according to these general
principles:
longMethodCall(expr1, expr2,
expr3, expr4, expr5);
PREFER:
var = a * b / (c - g + f) +
4 * z;
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.
b. 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. Better use tabs. Tab characters
have some advantages:
4. Comments
a. Block 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 :
/* 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 oldfashioned 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 preceeded by comments in the same line:
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 comment out large
sections of code.
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.
c. 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>
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'.
5. Declarations
a. Number of Declarations per Line
Do not put more than one variable or variables of different types on the same line when
declaring them. Example:
The above example also demonstrates the drawbacks of non-obvious variable names. Be
clear when naming variables.
b. Initialization
Try to initialize local variables as soon as they are declared. For example:
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:
b. 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;
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();
...
}
Note: Generally use brackets even if there is only one statement in the loop.
e. While/do-while Statements
while (condition)
{
...
}
while (condition) ;
A do-while statement should have the following form:
do
{
...
} while (condition);
f. Switch Statements
switch (condition)
{
case A:
...
break;
case B:
...
break;
default:
...
break;
}
g. Try-catch Statements
Or
try
{
...
}
catch (Exception e)
{
...
}
Or
try
{
...
}
catch (Exception e)
{
...
}
finally
{
...
}
7. White Space
a. 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:
b. Inter-term spacing
TestMethod( a, b, c );
Single spaces surround operators (except unary operators like increment or logical not),
example:
Use spaces for the table like formatting and not tabs because the table formatting may
look strange in special tab intent levels.
8. Naming Conventions
a. Capitalization Styles
i. Pascal Casing
This convention capitalizes the first character of each word (as in TestCounter).
This convention capitalizes the first character of each word except the first one. E.g.
testCounter.
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:
b. 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 btnCancel;
System.Windows.Forms.TextBox txtName;
System.Windows.Forms.Label lblName;
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
Use Pascal Casing (see 8.1.1)
x. Delegates
//Good
ImageChangedDelegate imageChanged = ChangeImage;
//Bad
ImageChangedDelegate imageChanged = new
ImageChangedDelegate(ChangeImage);
xi. Custom attributes - Suffix all attribute class names with Attribute. The
C# compiler recognizes this and allows you to omit it when using it.
xii. Generics
Generics, introduced in .NET 2.0, are classes that work uniformly on values of different
types.
//Good
public class Stack ‹T›
//Bad
public class Stack ‹t›
public class Stack ‹Type›
xiv. Miscellaneous
Avoid putting using statements inside a namespace
Check spelling in comments
Always start left curly brace { on a new line
Group framework namespaces together, add custom and thirdparty
namespaces below
Use strict indentation (3 or 4 spaces, no tabs)
Avoid fully qualified type names
Indent comment at the same line as the code
All member variables should be declared at the top of classes; properties and
methods should be separated by one line each
Declare local variables as close as possible to the first time they're used
File names should reflect the classes that they contain
Let's face it, we all do these things one time or another. Let's avoid them as best
as we can:
string myVar;
MyFunction();
4. Acronyms.
//AcronymFunction
AF();
//SuperFastAcronymFunction
SFAT()
DoThis();
DoThisWillYa();
6. Names starting with underscores. They look cool, but let's not ;)
int _m1 = 0;
string __m2 = "";
string _TempVariable = "";
8. Abbreviations.
string num;
int abr;
int i;
9. Programming Practices
a. 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.
b. 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 :
namespace ShowMeTheBracket
{
/// <summary>
/// Defines the different types of Test Values
/// </summary>
public enum Test
{
TestMe,
TestYou
}
/// <summary>
/// Defines the Members of the Class TestMeClass
/// </summary>
public class TestMeClass
{
/// <summary>
/// Represents an instance which holds the Test object.
/// </summary>
Test _test;
/// <summary>
/// Represents an instance which holds the value of String
/// </summary>
string _variableString = "";
/// <summary>
/// Gets or Sets the value of Test
/// </summary>
public Test Test
{
get
{
return _test;
}
set
{
_test = value;
}
}
/// <summary>
/// This Method is used to perform the test action
/// </summary>
public void PubMethoding(string ParamString, int ParamInt)
{
string testVariable= "";
if (_test == Test.TestMe)
{
//...stuff gets done
}
else
{
//...other stuff gets done
}
}
/// <summary>
/// This Method is used to perform the test action
/// </summary>
/// <param name="paramString">Represents an string
/// parameter which holds the value of the param1</param>
private void doSomething(string paramString)
{
string testVariable= "";
if (_test == Test.TestMe)
{
//...stuff gets done
}
else
{
//...other stuff gets done
}
}
}
}
b. Variable naming example
instead of :
}
for (int i = 0; i < num; ++i)
{
if (meetsCriteria[i])
{
Note: Indexer variables generally should be called i, j, k etc. But in cases like this, it may
make sense to reconsider this rule. In general, when the same counters or indexers are
reused, give them meaningful names.