Coding | specification 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 spaces
Naming conventions
Programming practices
Code examples
1. About the C # coding Style Guide
This document May is 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 if you write in even Ming language.
2. File Organization
2.1 C # SourceFiles
Keep your classes/files short, don ' t exceed LOC, divide your code up, make structures clearer. Put every class in a separate file and name the "file like" class name (with. cs as extension of course). This convention makes is things much easier.
2.2 Directory Layout
Create a directory for every namespace. (for MyProject.TestSuite.TestTier use Myproject/testsuite/testtier as the path, does not have the namespace name with dots.) This is makes it easier to map namespaces to the directory layout.
3. Indentation
3.1 Wrapping Lines
When a expression won't fit on a single line, break it up according to this general principles:
After the break a comma.
After the break of 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 ' the ' is preferred, since-the break occurs outside the paranthesized expression. This is the indent with tabs to the indentation level and then with spaces to the breaking in our position 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 the tab). A Good coding practice is to make the tab and spaces chars visible in the editor which are used.
3.2 White Spaces
An indentation standard using spaces never is achieved. Some people like 2 spaces, Some prefer 4 and others to 8, or die more even. 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'll reduce typing (even with smartindenting you have to set the IND Entation manually sometimes, or take it back or whatever)
If you are want to increase the indentation (or decrease), mark one blocks and increase the indent level with Tab with Shift-ta b You decrease the indentation. This is true to 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 is avoided. For descriptions with the///comments to give C # standard descriptions is recommended. When you are wish to use block comments your should use the following style:
/* Line 1 * Line 2 * Line 3 * *
As this is set off the blocks visually from code for the (human) reader. Alternatively you might use this oldfashioned the C style for single line comments, even though the it is not recommended. In case with this style, a line break should follow the comment, as it's hard to = to = Code preceeded by comments in the Same line:
/* blah blah blah * *
Block comments May is useful in rare cases, refer to the Technote ' fine Art of commenting ' for a example. Generally block comments are useful for comment out large of code.
4.2 Single line Comments
Should use the//comment style to "comment out" code (SharpDevelop has a key for it, alt+/). It May is used for commenting sections of code too.
Single line comments must is indented to the indent level when they are for code used. Commented out code should is commented out in the ' the ' the ' I to enhance ' visibility out code.
A rule of thumb says this generally, the length of a comment should not exceed the length of the code explained by too MUC H, as is a 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 to 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 is preceded by three slashes to be accepted as XML comment. Tags fall into two categories:
Documentation Items
Formatting/referencing
The category contains tags like <summary>, <param> or <exception>. These represent items this represent the elements of a program ' s API which must is documented for the "program" useful To the other programmers. These tags are usually have attributes such as name or CREF as demonstrated in the multiline example. These attributes are checked by the compiler, so they should to 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 to the Microsoft. NET Framework SDK documentation. For information on commenting best practice and further issues related to commenting, and the Technote ' fine Art of Co Mmenting '.
5. Declarations
5.1 Number of Declarations per line
One declaration per line is recommended since it encourages commenting1. In the other words,
int level; Indentation level int size; Size of table
Don't 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 drawbacks non-obvious of variable. Be clear when naming variables.
5.2 Initialization
Try to initialize the 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 the using statement:
using (OpenFileDialog OpenFileDialog = new OpenFileDialog ()) {...}
5.3 Class and Interface Declarations
When coding C # classes and interfaces, the following formatting rules should be followed:
No spaces 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.
For example:
Class Mysample:myclass, imyinterface {int myInt; public mysample (int myInt) {this.myint = myInt;} void Inc () {++myi nt } void Emptymethod () {}}
For a brace placement example look at section 10.1.
6. Statements
6.1 Simple statements
Each line should contain only one statement.
6.2 Return Statements
A return statement should to outer most parentheses. Don ' t use:
Return (n * (n + 1)/2); Use:return N * (n + 1)/2;
6.3 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 ();}
6.4 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 are only one statement in the loop.
6.5 while/do-while Statements
A While statement should is 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 Statements
A switch statement should be of following form:
Switch (condition) {case A: ... break, case B: ... break; default: ... break;
6.7 Try-catch Statements
A Try-catch statement should follow this form:
try {...} catch (Exception) {} or try {...} catch (Exception e) {...} or try {...} catch (Exception e) {...} fin Ally {...}
7. White spaces
7.1 Blank Lines
Blank lines improve readability. They set off blocks of the 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 is us Ed between:
Methods
Properties
Local variables in Alpha and its statement
Logical sections inside a method to improve readability note this blank lines must be indented as they would contain a STA Tement This makes insertion the lines much easier.
7.2 inter-term Spacing
There should is a single 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 < ++i)//don ' t use for (int i=0; i<10; ++i)//or//for (int i=0;i<10;++i)
7.3 Table like formatting
A logical block of lines should is formatted as a table:
String name = "Mr Ed"; int myvalue = 5; Test atest = test.testyou;
Use spaces to the table like formatting and not tabs because the table formatting may look strange in special tab intent Levels.
8. Naming conventions
8.1 Capitalization Styles
8.1.1 Pascal Casing
This convention capitalizes the "character" of each word (as in testcounter).
8.1.2 Camel Casing
This convention capitalizes the ' character ' of each word except the ' one. e.g. Testcounter.
8.1.3 Upper Case
Only use the upper case for identifiers if it consists of a 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 guidelines
Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation considered bad practice.
Hungarian notation is a defined set of the pre and postfixes which are the applied to names to reflect the type of the variable. This style of naming were widely used in early Windows programming, but??? obsolete or at least should be considered de Precated. The Using Hungarian notation is not allowed if to follow this guide.
and remember:a Good variable name describes the semantic not the type.
An exception to this is GUI code. All fields and variable names this contain GUI elements like button should is postfixed with their type name without Abbre Viations. For example:
System.Windows.Forms.Button CancelButton; System.Windows.Forms.TextBox nameTextBox;
8.2.1 Class Naming guidelines
Class names must be nouns or noun phrases.
Usepascal Casing and 8.1.1
Do no use any class prefix
8.2.2 Interface Naming guidelines
Name interfaces with nouns or noun phrases or adjectives describing. (Example IComponent or ienumberable)
Use Pascal casing (8.1.1)
Use I as prefix for the name, it's followed by a capital letter (the interface name)
8.2.3 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 the plural name for bit fields.
8.2.4 ReadOnly and Const Field Names
Name static fields with nouns, noun phrases or abbreviations for nouns
Use Pascal casing (8.1.1)
8.2.5 Parameter/non Const Field Names
Do use descriptive names, which should is 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 (8.1.2)
8.2.6 Variable Names
Counting variables are preferably called I, J, K, L, M, n when used in ' trivial ' counting loops. (10.2 for a example on the more intelligent naming for global counters etc.)
Use Camel casing (8.1.2)
8.2.7 Method Names
Name methods with verbs or verb phrases.
Use Pascal casing (8.1.2)
8.2.8 Property Names
The Name properties using nouns or noun phrases
Use Pascal casing (8.1.2)
Consider naming a property with the same name as it ' s type
8.2.9 Event Names
Name event handlers with the EventHandler suffix.
Use two parameters named sender and E
Use Pascal casing (8.1.1)
Name event argument classes with the EventArgs suffix.
Name event names that have a concept the pre and post using the present and past tense.
Consider naming events using a verb.
8.2.10 Capitalization Summary
Type Case Notes
Class/struct Pascal Casing
Interface Pascal casing starts with I
Enum Values Pascal Casing
Enum Type Pascal Casing
Events Pascal Casing
Exception class Pascal casing End With Exception
Public Fields Pascal Casing
Methods Pascal Casing
Namespace Pascal Casing
Property Pascal Casing
Protected/private Fields Camel Casing
Parameters Camel Casing
9. Programming practices
9.1 Visibility
Do is no instance or class variable public and make them private. For private members prefer not using "private" as modifier just does write nothing. Private is the "default case" and every C # programmer should be aware of it.
Use properties instead. You could use public static fields (or const) as a exception to this rule and but it should not being the rule.
9.2 No ' magic ' Numbers
Don ' t use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these later to changes (say, your application can now handle 3540 users instead of the 427 into your code in lines scattered Troughout your 25000) is LOC and Error-prone. Instead declare a const variable which contains the number:
public class MyMath {public Const double PI = 3.14159 ...}
Code examples
10.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 this, isnew in version 0.3 and is different in 0.2)
Class/interface/struct declarations
Method Declarations
10.2 Variable Naming Example
Instead of:
for (int i = 1; i < Num. ++i) {Meetscriteria[i] = true;} for (int i = 2; i < NUM/2; ++i) {Int J = i + i; (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; Factorab Lenumber + = factor; for (int primecandidate = 0; primecandidate < num; ++primecandidate) {if (isprime[primecandidate)) {Console.Write Line (Primecandidate + "is prime."); } }
Note:indexer variables generally should be called I, J, K etc. But In cases like this, the it may make sense to the reconsider this rule. In general, when the same counters or indexers are reused, give them and meaningful names.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.