C # Coding specification,

Source: Internet
Author: User

C # Coding specifications (reproduced ),

Original article: http://www.cnblogs.com/wulinfeng/archive/2012/08/31/2664720.html

 

1Purpose ............................................................... 3

2Applicability ............................................................... 3

3Code comments ............................................................... 3

3.1 code comments .................................... ........ 3

3.2 Module header comment specifications ...................................... 3

3.3 method annotation specifications .................................... ......... 4

3.4 code line comment specifications ................................... ....... 6

3.5 variable annotation specification .................................... ......... 7

4Naming rules ............................................................... 8

4.1 basic naming conventions ................................... ....... 8

4.2 basic conventions on various types of identifiers...

4.3 list of abbreviated component names ................................... .... 10

5Other specifications ............................................................... 11

5.1 programming style ..................................... ............. 11

5.2 release a resource ..................................... ............. 13

5.3 handle errors ..................................... ............. 13

5.4 other ...................................... ................... 14

1Purpose

2Applicability

3Code comment

3.1Code comments

3.2Module header annotation Specification

A module header annotation specification is required for all physical files, for example, C #In. CsFile

Description of the beginning of each module, mainly including :(Bold ChineseIs required, and the rest is optional)

Example:

3.3Method annotation Specification

1> C # provides a mechanism for programmers to write documents for their code using the special annotation syntax containing XML text. In the source code file, annotations with some format can be used to guide a tool to generate XML based on these annotations and the source code elements behind them. In a specific application, classes, interfaces, attributes, and methods must have the <Summary> section. In addition, if methods have parameters and return values, they must have the <Param> and <Returns> sections. Example:

/// <Summary>

///...

/// </Summary>

/// <Param name = ""> </param>

/// <Returns> </returns>

2> when an event does not require a header annotation, but contains complex processing (such as loops, database operations, and complex logic), the event should be split into a single processing function and then called.

3> all methods must be added with method comments before their definition.

4> method annotations automatically generate annotations in XML tag format in the form.

Mark

Description

Remarks

<C>

Provides a way to mark the text in the description as code

<Code>

Provides a method to indicate multiple lines as code.

<Example>

You can specify the usage method or examples of other library members. Generally, this involves the use of the <code> flag.

<Exception>

References to exceptions that can be obtained from the current compilation environment.

<Include>

You can reference comments in another file describing types and members in source code.

<List>

Used to define the title row in a table or definition list.

<Para>

Used in a tag such as <summary>, <remarks>, or <returns>, you can add the structure to the text.

<Param>

It should be used in the annotation of the method declaration to describe a parameter of the method.

<Paramref>

Provides a method to specify parameters.

<Permission>

Member access is recorded in the document.

<Remarks>

Adds information about a type to supplement the information specified by <summary>.

<Returns>

It should be used for annotation of method declaration to describe the return value.

<See>

The link can be specified from the text.

<Seealso>

References to members or fields that can be called through the current compilation environment.

<Summary>

It should be used to describe type or type members.

<Value>

Attribute description.

The following figure shows an example:

5> in a public class library, the public method must add the author, date, and modification record information after the comment of the general method. The labels are added in the XML tag format as follows:

<Author> </Author> Author

<CreateDate> </CreateDate> creation date

<RevisionHistory> modify record

<ModifyBy> </ModifyBy> modify author

<ModifyDate> </ModifyDate> modification date

<ModifyReason> </ModifyReason> reason for Modification

<ModifyBy> </ModifyBy> modify author

<ModifyDate> </ModifyDate> modification date

<ModifyReason> </ModifyReason> reason for Modification

<ModifyBy> </ModifyBy> modify author

<ModifyDate> </ModifyDate> modification date

<ModifyReason> </ModifyReason> reason for Modification

</RevisionHistory>

<LastModifyDate> </LastModifyDate> last modification date

6> If a code file is written by one person, the methods in this code file do not require the author information. Non-code file authors must add author, date, and other comments when adding methods to this file.

7> to modify any method, you must add a comment for the modification record.

3.4Code line comment Specification

1> if processing a function requires many lines of code implementation and many logical structure blocks, such code should be annotated before the Code starts, describes how to handle the block code and precautions.

2> Add comments from the new line and align them left at the beginning of the Code

3> separate the double slashes and comments with spaces, as shown in the following figure:

3.5Variable annotation Specification

1> when defining a variable, you must add a variable comment to describe the usage of the variable.

2> Class-level variables should automatically generate comments in XML tag format in the form of //, as shown in the following figure:

3> method-level variable comments can be placed behind the variable declaration statement. They are left aligned with the comments of the variable declaration at the front and back ends. The comments and codes are separated by tabs.

4Naming rules

4.1Naming Conventions

1> use a complete English descriptor that accurately describes the variables, fields, and classes, such as firstName. You can use simple names for variables that have obvious functions. For example, incremental (subtract) variables in a loop can be named "I ".

2> try to use the terms in the fields involved in the project.

3> use a mix of upper and lower cases to improve the readability of the name. To distinguish multiple words in an identifier, the first letter of each word in the identifier is capitalized. Do not use underscores to separate characters.

There are two suitable writing methods for different types of identifiers:

PasalCasing:Uppercase letters of the first word of the identifier;

CamelCasing:The lowercase letter of the first word of the identifier.

4> The following table describes the case sensitivity rules for different types of identifiers:

Identifier

Case sensitivity

Example

Namespace

Pascal

Namespace Com. Techstar. ProductionCenter

Type

Pascal

Public class DevsList

Interface

Pascal

Public interface ITableModel

Method

Pascal

Public void UpdateData ()

Attribute

Pascal

Public int Length {...}

Event

Pascal

Public event EventHandler Changed;

Private Field

Camel

Private string fieldName;

Non-private field

Pascal

Public string FieldName;

Enumerated Value

Pascal

FileMode {Append}

Parameters

Camel

Public void UpdateData (string fieldName)

Local variable

Camel

String fieldName;

5> avoid using abbreviations. If you must use them, use them with caution. At the same time, a list of standard abbreviations should be retained and kept consistent during use.

6> for Common acronyms, The abbreviations of the two letters must be case-insensitive (for example, ioStream and getIOStream). For multi-letter abbreviations, the first letter and the other letters are in lowercase (for example: getHtmlTag );

7> avoid using long names (preferably up to 15 letters ).

8> avoid using similar or case-sensitive names.

4.2Naming Conventions for various Identifier Types

1>Assembly name

Lab name + project name + Module name (optional), for example:

Central Server Assembly: Lab. SeverCenter;

Central server Business logic Assembly: Lab. SeverCenter. Business;

2>Namespace

In the same way as the Assembly name: Lab name + project name + Module name. In addition, it is generally recommended that the namespace and directory structure be the same. For example:

Central Server: Lab. SeverCenter;

User Control under the central server: Lab. SeverCenter. UserControl;

Business logic of the central server: Lab. SeverCenter. Business;

Central Server Data Access: Lab. SeverCenter. Data;

3>Assembly and DLL

L in most cases, an Assembly contains all or part of reusable libraries and is contained in a single dynamic link library (DLL.

L an assembly can be split into multiple DLL files, but this is rare and is not described in this criterion.

L The Assembly and DLL are the physical organization of the library, while the namespace is the logical organization. Their composition should be independent of the Assembly's organization.

L The namespace can and often spans multiple sets. You can consider the following mode to name the DLL:

<Company>. <Component>. dll

Example: Lab. SeverCenter. dll

4>Class and Interface Name

The class name should be a noun;

L avoid using the abbreviation of a word unless it is widely known, such as HTTP.

L The interface name must start with the letter I. Ensure that the standard implementation names of interfaces differ only by one "I" prefix. For example, the standard IMPLEMENTATION OF THE IComponent interface is Component;

L generic type parameter name: enter a descriptive name starting with T or T, for example:

Public class List <T>

Public class MyClass <Tsession>

L name the classes in different namespaces of the same project to avoid duplication. Avoid Conflicts and obfuscation during reference;

5>Method Name

L The first word is generally a verb;

L if the method returns the value of a member variable, the method name Is generally the Get + member variable name. If the returned value Is a bool variable, it Is generally prefixed with "Is. In addition, if necessary, consider using attributes as an alternative;

L if the method modifies the value of a member variable, the method name is generally Set + member variable name. Same as above. Consider using attributes to replace methods.

6>Variable name

L according to the scope of use, the variables in our code basically have the following types: public variables of the class; private variables of the class (protected and public); parameter variables of the method; local variables used inside the method. The naming rules for these variables are basically the same. For more information, see the identifier case sensitivity table. The differences are as follows:

A) The public variables of the class are named in the usual way, with no special requirements;

B) private variables of the class can be used in either of the following ways: use the "m" prefix, for example, mWorkerName;

C) The parameter variables of the method use camalString, for example, workerName;

L local variables in the method use camalString, such as workerName.

L do not use _ or & as the first letter;

L use short and meaningful words whenever possible;

L single-character variable names are generally only used for very short-lived variables: I, j, k, m, n is generally used for integer; c, d, e is generally used for characters; s is used for string

L if the variable is a set, the variable name must use the plural number. For example, the number of rows in a table should be named RowsCount;

L The naming component should adopt the Hungarian naming method. All prefixes should follow the abbreviation list of the same component name.

4.3List of abbreviated component names

The basic principle of abbreviations is to take the first letter of each word in the component class name. If there is only one word, remove the vowels and leave the consonants. All abbreviations are in lower case.

Component Type

Abbreviations

Example

Label

Lbl

LblNote

TextBox

Txt

TxtName

Button

Btn

BtnOK

ImageButton

Ib

IbOK

LinkButton

Lb

LbJump

HyperLink

Hl

HlJump

DropDownList

Ddl

DdlList

CheckBox

Cb

CbChoice

CheckBoxList

Cbl

CblGroup

RadioButton

Rb

RbChoice

RadioButtonList

Rbl

RblGroup

Image

Img

ImgBeauty

Panel

Pnl

PnlTree

TreeView

TV

TvUnit

WebComTable

Wct

WctBasic

ImageDateTimeInput

MHD

DtiStart

ComboBox

Cb

CbList

MyImageButton

Mib

MibOK

WebComm. TreeView

TV

TvUnit

PageBar

Pb

PbMaster

5Other Specifications

5.1 programming style

1>Variable declaration:

To maintain better reading habits, do not write multiple variable declarations in one row, that is, one row declares only one variable.

For example:

String strTest1, strTest2;

Should be written:

String strTest1;

String strTest2;

2>Code indent:

L consistent code indent style facilitates the expression of the code structure hierarchy, making the code easier to read and pass;

L code indentation is implemented using the Tab key. It is best not to use spaces. To ensure that the Code indentation is consistent on different machines, the Tab key width of C # is set to 4 characters, the setting interface is as follows (tool-option ):

L avoid more than five parameters in the method. Generally, it is recommended to use two or three parameters. If this parameter is exceeded, use struct to pass multiple parameters.

L for easier reading, the code line should not be too long. The best width is the screen width (the visible width varies depending on the display resolution ). Please do not exceed the screen width you are using. (Each line of code should not exceed 80 characters .)

L The goto statement should not be used in the program.

L in the switch statement, the default clause is always required to display information.

L when there are more than 8 method parameters, the structure or class is used for transmission.

L The operator/operator has a space left and right.

L place the {} numbers of all blocks in one row, and place them in nested alignment. Do not place them on the same row.

3>Blank:

L empty lines separate the segments related to the logic to improve readability.

L two empty rows should always be used in the following cases:

A) two sections of a source file.

B) between class declaration and interface declaration.

L a blank line should always be used in the following cases:

A) between two methods.

B) between the local variable in the method and the first statement of the method.

C) block comments (see "5.1.1") or single line comments (see "5.1.2.

D) Two Logical segments in a method to improve readability.

L spaces should always be used in the following cases:

A) the blank space should be placed behind the comma in the parameter list, for example:

Void UpdateData (int a, int B)

B) all binary operators except "." should be separated by spaces. There is no space between the unary operator and the operand, for example, minus sign ("-"), auto-increment ("++"), and auto-subtraction ("--"). For example:

A + = c + d;

D ++;

C) The expressions in the for statement should be separated by spaces. for example:

For (expr1; expr2; expr3)

D) A space should be followed after forced transformation, for example:

Char c;

Int a = 1;

C = (char);

5.2Resource release

All external resources must be explicitly released. For example, database connection objects and IO objects.

5.3Error Handling

1> do not "catch exceptions but do nothing". If an exception is hidden, you will never know whether the exception has occurred.

2> when an exception occurs, a friendly message should be provided to the user, but all possible details of the error should be recorded precisely, including the time when the error occurred, related methods, and class names.

3> only capture specific exceptions, rather than general exceptions.

Correct practice:

Incorrect practice:

5.4Others

1> one method only completes one task. Do not combine multiple tasks into one method, even if those tasks are very small.

2> use the special type of C # instead of the alias type defined in the System namespace.

3> do not use a fixed value in the program, instead of a constant.

4> avoid using many member variables. Declare local variables and pass them to methods. Do not share member variables between methods. If a member variable is shared among several methods, it is difficult to know which method modifies its value.

5> do not declare the member variables as public or protected. Are declared as private and use the public/protected attribute

6> do not use the specific path and drive name in the code. Use relative paths and make the paths programmable.

7> perform "self-check" when the application starts and ensure that the required files and attachments are in the specified position. Check the database connection if necessary. If any problem occurs, give the user a friendly prompt.

8> If the required configuration file cannot be found, the application must be able to create a copy using the default value.

9> if an error value is found in the configuration file, the application will throw an error and a message will be prompted to tell the user the correct value.

10> when using DataColumn to retrieve its column, you must use the field name instead of the index number.
For example, correct DataColumn ["Name"]
Bad DataColumn [0]

11> in a class, all field definitions are placed before the class header and all methods or attributes.

12> in a class, all attributes are defined in one attribute block:

Version: 1.0.0

Date: 2012.8.30

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.