C # coding specification

xiaoxiao2021-03-06  125

Guess a mystery first.

Two ants were slowly climbing together, and suddenly an ants found a big pear. (Guess the name of the two countries)

The answer is not in the article

Technotes, HOWTO SERIES

C # Coding style guide

Version 0.3by 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, do not 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 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 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 WA .. S 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 thing for almost any TextEditor. Here, We define the Tab as The standard Indentation Character.

Don't use space 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 TO. Single Line Comment s must be indented to the indent level when they are used 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 for 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: ///// This class ... /// Multiline XML Comments Follow this pattern: ///

/// This exception gets thrown as soon as a /// Bogus flag gets set /// 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

. 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 The Should Be Valid. The Latter Category Governs The Layout of The Documentation, Using Tags Such As

,

oral

.

Documentation Can death '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 5.1 Number of 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 Decing The M. EXAMPLE: INT A, B; // What Is' A? What does' b 'Stand for? The Above Example Also Demonstrates The Above Example Also Demonstrates The Drawbacks of Non-Obvious 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; or int val = time.Hours; Note: If you initialize a dialog try to use 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 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 6. Statements 6.1 Simple Statements Each line should contain only one statement 6.2. Return Statements a returnost kindhers. 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) {DOSMETHING (); ...} f (condition) {DOSMETHING ); else {dosomethingother (); ...} f (condition) {DOSMETHING (); ...} else if (condition) {dosomethingother (); ...} else {dosomething PortaGain () ;. .} 6.4 for / foreach statementsa for statement shoud following form: for (int i = 0; i <5; i) {...} or single limited (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 is only one statement in the loop 6.5 While / do-while StatementsA while statement should. BE (condition) {...} an Empty While Should Have The Following Form: While (condition); a do-while statement shop Have The Following form: do {...} while (condition); 6.6 Switch Statementsa Switch Statement S Hould Be of Following Form: Switch (Condition) {Case A: ... Break; Case B: ... Break; Default: ... Break;

} 6.7 Try-catch statements a try-catch statement shop folow this form: try {...} catch (exception) {} or try {...} catch (exception e) {...} or try {.. .} catch (Exception e) {...} finally {...} 7. White Space 7.1 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 7.2 Inter-term spacingThere should be a single space 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 <10; 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 BE FORMATTED AS A Table: String name = "mr. ed"; int myvalue = 5; test activ = 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 Conventions 8.1 Capitalization Styles 8.1.1 Pascal Casing This convention capitalizes the first character of each word (as in TestCounter). 8.1.2 Camel Casing This convention capitalizes the first character of each word except the first one. Eg testCounter. 8.1.3 Upper case 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:. 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 accounting 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 Th . E 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 Guidelines Class names must be nouns or noun phrases. UsePascal Casing see 8.1.1 Do not use any class prefix 8.2.2 Interface Naming Guidelines 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) 8.2.3 enum Naming Guidelines Use Pascal Casing for enum 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 names name static fields with nouns, noun phrases or abbreviations for nouns Use Pascal Casing ( see 8.1.1) 8.2.5 Parameter / non const field names 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) 8.2.6 Variable N Ames Counting Variables Are Preference Called i, J, K, L, M, N by 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) 8.2.7 Method Names Name methods with verbs or verb phrases. Use Pascal Casing (see 8.1.2) 8.2.8 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 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 (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 Practices 9.1 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. 9.2 No 'magic' Numbers Do not 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 Uses 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 Examples 10.1 Brace placement example namespace ShowMeTheBracket {public ENUM TEST {TestMe, TestYou} public class testmedmeclass {test; public test test; get {reet = value;}} void dosomething ()} void dosomething ()} void dosomething ()} void dosomething ()} void doomet

转载请注明原文地址:https://www.9cbs.com/read-126933.html

New Post(0)