Technotes, HowTo Series
C# Coding Style Guide
Version 0.3
by Mike Krüger icsharpcode.net
- About the C# Coding Style Guide
- File Organization
- Indentation
- Comments
- Declarations
- Statements
- White Space
- Naming Conventions
- Programming Practices
- Code Examples
1. About the 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
2.1 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.
2.2 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.
3. Indentation
3.1 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:
` 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.
3.2 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:
- Everyone can set their own preferred indentation level
- 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)
- 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!
4. Comments
4.1 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:
/* 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 comment out large sections of code.
4.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. 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.
4.3 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:
///
1<summary> /// This class... /// </summary>
Multiline XML comments follow this pattern:
///
1<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
1<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>.
2Documentation can then be generated using the 'documentation' item in the #develop 'build' menu. The documentation generated is in HTMLHelp format.
3For 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'.
4
5# 5\. Declarations
6
7### 5.1 Number of Declarations per Line
8
9One declaration per line is recommended since it encourages commenting1. In other words,
10
11
12 int level; // indentation level int size; // size of table
13
14Do not put more than one variable or variables of different types on the same line when declaring them. Example:
15
16
17 int a, b; //What is 'a'? What does 'b' stand for?
18
19The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.
20
21### 5.2 Initialization
22
23Try to initialize local variables as soon as they are declared. For example:
24
25
26 string name = myObject.Name;
27
28or
29
30
31 int val = time.Hours;
32
33Note: If you initialize a dialog try to use the using statement:
34
35
36 using (OpenFileDialog openFileDialog = new OpenFileDialog()) { ... }
37
38### 5.3 Class and Interface Declarations
39
40When coding C# classes and interfaces, the following formatting rules should be followed:
41
42* No space between a method name and the parenthesis " (" starting its parameter list.
43* The opening brace "{" appears in the next line after the declaration statement
44* The closing brace "}" starts a line by itself indented to match its corresponding opening brace.
45
46For example:
47
48
49 Class MySample : MyClass, IMyInterface { int myInt; public MySample(int myInt) { this.myInt = myInt ; } void Inc() { ++myInt; } void EmptyMethod() { } }
50
51For a brace placement example look at section 10.1.
52
53# 6\. Statements
54
55### 6.1 Simple Statements
56
57Each line should contain only one statement.
58
59### 6.2 Return Statements
60
61A return statement should not use outer most parentheses. Don't use :
62
63
64 return (n * (n + 1) / 2); use : return n * (n + 1) / 2;
65
66### 6.3 If, if-else, if else-if else Statements
67
68if, if-else and if else-if else statements should look like this:
69
70
71 if (condition) { DoSomething(); ... } if (condition) { DoSomething(); ... } else { DoSomethingOther(); ... } if (condition) { DoSomething(); ... } else if (condition) { DoSomethingOther(); ... } else { DoSomethingOtherAgain(); ... }
72
73### 6.4 For / Foreach Statements
74
75A for statement shoud have following form :
76
77
78 for (int i = 0; i < 5; ++i) { ... }
79
80or single lined (consider using a while statement instead) :
81
82
83 for (initialization; condition; update) ; A foreach should look like : foreach (int i in IntList) { ... }
84
85Note: Generally use brackets even if there is only one statement in the loop.
86
87### 6.5 While/do-while Statements
88
89A while statement should be written as follows:
90
91
92 while (condition) { ... }
93
94An empty while should have the following form:
95
96
97 while (condition) ;
98
99A do-while statement should have the following form:
100
101
102 do { ... } while (condition);
103
104### 6.6 Switch Statements
105
106A switch statement should be of following form:
107
108
109 switch (condition) { case A: ... break; case B: ... break; default: ... break; }
110
111### 6.7 Try-catch Statements
112
113A try-catch statement should follow this form:
114
115
116 try { ... } catch (Exception) {} or try { ... } catch (Exception e) { ... } or try { ... } catch (Exception e) { ... } finally { ... }
117
118# 7\. White Space
119
120### 7.1 Blank Lines
121
122Blank lines improve readability. They set off blocks of code which are in themselves logically related. Two blank lines should always be used between:
123
124* Logical sections of a source file
125* Class and interface definitions (try one class/interface per file to prevent this case) One blank line should always be used between:
126* Methods
127* Properties
128* Local variables in a method and its first statement
129* 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.
130
131### 7.2 Inter-term spacing
132
133There should be a single space after a comma or a semicolon, for example:
134
135
136 TestMethod(a, b, c); don't use : TestMethod(a,b,c)
137
138or
139
140
141 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)
142
143### 7.3 Table like formatting
144
145A logical block of lines should be formatted as a table:
146
147
148 string name = "Mr. Ed"; int myValue = 5; Test aTest = Test.TestYou;
149
150Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.
151
152# 8\. Naming Conventions
153
154### 8.1 Capitalization Styles
155
156### 8.1.1 Pascal Casing
157
158This convention capitalizes the first character of each word (as in TestCounter).
159
160### 8.1.2 Camel Casing
161
162This convention capitalizes the first character of each word except the first one. E.g. testCounter.
163
164### 8.1.3 Upper case
165
166Only 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:
167
168
169 public class Math { public const PI = ... public const E = ... public const feigenBaumNumber = ... }
170
171### 8.2. Naming Guidelines
172
173Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice.
174
175Hungarian 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.
176
177And remember: a good variable name describes the semantic not the type.
178
179An 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:
180
181
182 System.Windows.Forms.Button cancelButton; System.Windows.Forms.TextBox nameTextBox;
183
184### 8.2.1 Class Naming Guidelines
185
186* Class names must be nouns or noun phrases.
187* UsePascal Casing see 8.1.1
188* Do not use any class prefix
189
190### 8.2.2 Interface Naming Guidelines
191
192* Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
193* Use Pascal Casing (see 8.1.1)
194* Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)
195
196### 8.2.3 Enum Naming Guidelines
197
198* Use Pascal Casing for enum value names and enum type names
199* Don’t prefix (or suffix) a enum type or enum values
200* Use singular names for enums
201* Use plural name for bit fields.
202
203### 8.2.4 ReadOnly and Const Field Names
204
205* Name static fields with nouns, noun phrases or abbreviations for nouns
206* Use Pascal Casing (see 8.1.1)
207
208### 8.2.5 Parameter/non const field Names
209
210* 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.
211* Use Camel Casing (see 8.1.2)
212
213### 8.2.6 Variable Names
214
215* 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.)
216* Use Camel Casing (see 8.1.2)
217
218### 8.2.7 Method Names
219
220* Name methods with verbs or verb phrases.
221* Use Pascal Casing (see 8.1.2)
222
223### 8.2.8 Property Names
224
225* Name properties using nouns or noun phrases
226* Use Pascal Casing (see 8.1.2)
227* Consider naming a property with the same name as it’s type
228
229### 8.2.9 Event Names
230
231* Name event handlers with the EventHandler suffix.
232* Use two parameters named sender and e
233* Use Pascal Casing (see 8.1.1)
234* Name event argument classes with the EventArgs suffix.
235* Name event names that have a concept of pre and post using the present and past tense.
236* Consider naming events using a verb.
237
238### 8.2.10 Capitalization summary
239
240Type | Case | Notes | | Class / Struct | Pascal Casing |
241---|---|---
242Interface | Pascal Casing | Starts with I
243Enum values | Pascal Casing |
244Enum type | Pascal Casing |
245Events | Pascal Casing |
246Exception class | Pascal Casing | End with Exception
247public Fields | Pascal Casing |
248Methods | Pascal Casing |
249Namespace | Pascal Casing |
250Property | Pascal Casing |
251Protected/private Fields | Camel Casing |
252Parameters | Camel Casing |
253
254# 9\. Programming Practices
255
256### 9.1 Visibility
257
258Do 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.
259
260Use properties instead. You may use public static fields (or const) as an exception to this rule, but it should not be the rule.
261
262### 9.2 No 'magic' Numbers
263
264Don’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 :
265
266
267 public class MyMath { public const double PI = 3.14159... }
268
269# 10\. Code Examples
270
271### 10.1 Brace placement example
272
273
274 namespace ShowMeTheBracket { public enum Test { TestMe, TestYou } public class TestMeClass { Test test; public Test Test { get { return test; } set { test = value; } } void DoSomething() { if (test == Test.TestMe) { //...stuff gets done } else { //...other stuff gets done } } } }
275
276Brackets should begin on a new line only after:
277* Namespace declarations (note that this isnew in version 0.3 and was different in 0.2)
278* Class/ Interface / Struct declarations
279* Method Declarations
280
281### 10.2 Variable naming example
282
283instead of :
284
285
286 for (int i = 1; i < num; ++i) { meetsCriteria[i] = true; } for (int i = 2; i < num / 2; ++i) { int j = i + i; while (j <= num) { meetsCriteria[j] = false; j += i; } } for (int i = 0; i < num; ++i) { if (meetsCriteria[i]) { Console.WriteLine(i + " meets criteria"); } } try intelligent naming : for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate) { isPrime[primeCandidate] = true; } for (int factor = 2; factor < num / 2; ++factor) { int factorableNumber = factor + factor; while (factorableNumber <= num) { isPrime[factorableNumber] = false; factorableNumber += factor; } } for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate) { if (isPrime[primeCandidate]) { Console.WriteLine(primeCandidate + " is prime."); } }
287
288Note: 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.</para></list></code></exception></summary>