C # coding style guideversion 0.3by mike krüger ICsharpcode.net
About the c # coding style guide ........................................ ..................................... 1 File Organization ........ ................................................ ................................................ .1 indentation ........................................... ................................................ ..................... 2 Comments ........................... ................................................ ....................................... 3 Declarations ....... ................................................ ................................................ ......... 4 STATEMENTS ................................... ................................................ ........................... 5 White Space .................. ................................................ ............................................. 7 Naming Conventions ................................................ ......................................... ............ 9 programming practices ................................... ................................................ .............. 11 code example ................................. ................................................ ......................... 12 1. About The C # Coding Style 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 Organization2.1 C # SourcefilesKeep 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 LayoutCreate 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. Indentation3.1 Wrapping LinesWhen 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 '>' is Tab Chars and '.' Are Spaces (The Spaces After Tab). A Good Coding Practice Is To Make The Tab and Space Chars Visible In The Editor Which IS Used. 3.2 White SpacesAn 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. Comments4.1 Block CommentsBlock 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 precededed 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 CommentsYou 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 CommentsIn 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: ///
/// this class ...
/// summary>
MultiLine XML Comments Follow this pattern:
///
/// 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 ,
or
Int size; // size of table
Do Not Put More Than One Variable or Variables of Different Types on The Same Line When Decilaning Them. EXAMPLE:
Int a, b; // What is 'a'? What does 'b' Stand for?
The Above Example Also Demonstrate Variable Names. Be Clear When Naming Variables. 5.2 InitializationTry To Initialize Local Variables As Soon As They Are Declared. For Example:
String name = myObject.name;
oral
INT VAL = Time.Hours;
Note: if you initialize a dialog try to use the using statement: use (OpenFiledialog OpenFiledialog = New OpenFileDialog () {
...
}
5.3 Class and Interface DeclarationsWhen 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. Starts a line "}" 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.6 Statements6.1 Simple StatementsEach line should contain only one statement 6.2 Return StatementsA return statement should not use outer most parentheses Do not use.:
Return (N * (N 1) / 2);
Use: return n * (n 1) / 2;
6.3 IF, IF-ELSE, IF ELSE-IF ELSE STATEMENTSIF, IF-ELSE AND IF ELSE-IF ELSE STATEments SHOULD LOOK LIKE THIS:
IF (Condition) {
DOSMETHING ();
...
}
IF (Condition) {
DOSMETHING ();
...
} else {
DOSMETHINGOTHER ();
...
}
IF (Condition) {
DOSMETHING ();
...
} else if (condition) {
DOSMETHINGOTHER ();
...
} else {
DOSMETHINGOTHERAGAIN ();
...
}
6.4 For / Foreach Statementsa for Statement SHOUD HAVE FOLLOWING FORM:
For (int i = 0; i <5; i) {
...
}
OR Single Lined (Consider Using A While Statement Instead):
For (Initialization; Update);
A foreach shouth look like:
Foreach (int I in intest) {
...
}
NOTE: Generally Use Brackets Even IF The Loop. 6.5 While / Do-While Statementsa 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);
6.6 Switch Statementsa Switch Statement SHOULD BE OF FOLLOWING FORM:
Switch (condition) {
Case A:
...
Break;
Case B:
...
Break;
DEFAULT:
...
Break;
}
6.7 Try-Catch Statementsa Try-Catch Statement Should Follow this form:
Try {
...
} catch (exception) {}
oral
Try {
...
} catch (exception e) {
...
}
oral
Try {
...
} catch (exception e) {
...
} finally {
...
}
.. 7. White Space7.1 Blank LinesBlank 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. 7.2 Inter-Term SpacingThere SHOULD BE A SINGLE SPACINGTH A COMMA OR A SEMICOLON, FOR EXAMPLE:
TestMethod (a, b, c); don't usemeth (A, B, C)
oral
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) 7.3 Table Like Formattinga Logical Block of Lines Should Be Formatted As a Table:
String name = "Mr. ED";
INT myValue = 5;
Test steest = test.testyou;
Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels. 8. Naming Conventions8.1 Capitalization Styles8.1.1 Pascal CasingThis convention capitalizes the first character of each word (as in TestCounter) .8.1 .2 Camel CasingThis convention capitalizes the first character of each word except the first one. Eg testCounter. 8.1.3 Upper caseOnly 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 = ...
}
8.2. Naming GuidelinesGenerally 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; 8.2.1 Class Naming GuidelinesClass names must be nouns or noun phrases UsePascal Casing see 8.1.1 Do not use any class prefix 8.2.2 Interface Naming GuidelinesName 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) 8.2.3 enum Naming GuidelinesUse Pascal Casing enum for value names and enum type names Do not prefix (or suffix) a enum type or enum values Use singular names for enums Use plural name for bit fields. 8.2.4 ReadOnly and Const Field NamesName static fields with nouns, noun phrases or abbreviations for nouns use Pascal Casing (see 8.1.1) 8.2.5 Parameter / non const field NamesDo 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) 8.2.6 Variable Namescounting Variables Are Preference Called i, J, K, L, M, N by buy 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) 8.2.7 Method NamesName methods with verbs or verb phrases. Use Pascal Casing (see 8.1.2) 8.2 .8 Property NamesName properties using nouns or noun phrases Use Pascal Casing (see 8.1.2) Consider naming a property with the same name as it's type 8.2.9 Event NamesName event handlers with the EventHandler suffix. 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. 8.2.10 Capitalization summary
TypeCaseNotesClass / StructPascal Casing InterfacePascal CasingStarts with IEnum valuesPascal Casing Enum typePascal Casing EventsPascal Casing Exception classPascal CasingEnd with Exceptionpublic FieldsPascal Casing MethodsPascal Casing NamespacePascal Casing PropertyPascal Casing Protected / private FieldsCamel Casing ParametersCamel Casing 9. Programming Practices9.1 VisibilityDo 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. 9.2 No 'magic' NumbersDon't use magic numbers, ie 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 ...
}
10. Code Examples10.1 Brace Placement Example
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
}
}
}
}
Brackets should begin on a new line only after: Namespace declarations (note that this isnew in version 0.3 and was different in 0.2) Class / Interface / Struct declarations Method Declarations 10.2 Variable naming exampleinstead of: for (int i = 1; i Meetscriteria [I] = true; } For (int i = 2; i INT j = i i; While (j <= num) { Meetscriteria [J] = false; J = I; } } For (int i = 0; i IF (Meetscriteria [I]) { Console.writeLine (i "Meets criteria); } } Try Intelligent Naming: For (int priMecandidate = 1; primecandidate { Isprime [primecandidate] = true; } For (int factor = 2; factory INT FACTORABLENUMBER = Factor Factor; While (Factorablenumber <= NUM) { Isprime [Factorablenumber] = false; Factorablenumber = factor; } } For (int priMecandidate = 0; primecandidate { IF (isprime [primecandidate]) { Console.writeline (Primecandidate "is prime.") } } 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.