C # code Specification-Programming Secrets

Source: Internet
Author: User
Tags uppercase letter

Original address: https://www.cnblogs.com/zzp0320/p/6949973.html

1. Introduction

This article is a set of development specifications that should be followed for C # Programmer and C # Developer development

Developing C # Programs According to this specification provides the following benefits:

The code is written to maintain consistency, improve the readability and maintainability of the Code, and in the case of a team developing a project, code sharing between programmers, easy code review

This specification is a first edition, applies only to general conditions of the general specification, and does not cover all situations

2. Document organization

2.1c# source File

The class name or file name should be short, not more than 2000LOC, splitting the code so that the structure is clear. Put each class in a separate file, using the class name to name the file name (of course, the extension is. cs), which makes it easier for everyone to work

2.2 Catalogue Design

Create a directory for each namespace. (using Myproject/testsuite/testtier as the path to the MyProject.TestSuite.TestTier instead of the namespace name with a dot) makes it easier to map namespaces to directories

Hierarchical Division.

3. Indent

3.1 Line break

When an expression exceeds one line, it is handled according to these general principles:

Wrap the line after the comma, wrap the line after the operator, wrap the line at the top, and do not wrap at the lower level, and then align the start position of the expression at the same level as the previous line statement.

Method invocation Line Break Example:

Longmethodcall (EXPR1,EXPR2,EXPR3,EXPR4,EXPR5);

Example of an arithmetic expression line break:

Recommended:

var = a * b/(c-g + f) +

4 * z;

Bad format--should avoid:

var = a * b/(c-g +

f) + 4 * z;

The first method is recommended, because it is a wrap (high-level wrapping principle) outside of the bracket expression. Note that you want to use a tab to indent the position, and then use a space to position the line. In our case, it is:

> var = a * b/(c-g + f) +

> ... 4 * z;

' > ' means a tab, '. ' Represents a space character. (a tab is followed by a tab indent). A good coding habit is to display tabs and whitespace in the editor you are using.

3.2 Blanks

There has never been a uniform standard for indenting with spaces. Some people like to use two spaces, some people like to use four spaces and some people like to use eight spaces, even some people like to use more space. A good practice is to use a tab. Tabs have some advantages:

· Everyone can set their own favorite level of indentation.

· It is just 1 characters instead of 2,4,8 and so on, so it will reduce the input (even because of auto indent, sometimes you have to set indent or cancel settings manually, and so on and so forth).

· If you want to increase or decrease indentation, you can mark a piece, use tab to increase the indent level, and use Shift-tab to reduce the indentation level. This is almost always true for any text editor.

Here, we define tab characters as standard indents.

Do not indent with spaces-with tabs!

4. Comments

4.1 Block Notes

Block annotations should usually be avoided. It is recommended to use///comments as standard C # declarations. If you want to use block annotations, you should use the following styles:

/*line1

*line2

*line3

*/

This allows the reader to separate the comment block from the code block. While it's not recommended to use a C-style single-line comment, you can still use it. Once in this way, there should be a line break after the comment lines because it is difficult to see the code that preceded the comment in the same line

/*blah blah blah * *

Block annotations are useful in rare cases. Usually block annotations are used to comment out large code Snippets

4.2 Single-line comment

You should use//annotation style "commented out" code (shortcut key, alt+/), it can also be used in the comment section of the code

A single-line comment is used for code descriptions and must be indented to the appropriate level of input. Commented out code should be placed in the first line is commented out so that the commented out code easier to see

An experience where the length of the comment should not exceed the length of the interpreted code because it indicates that the code is too complex and has a potential bug

4.3 File comments

In the. NET Framework, Microsoft has introduced a file that is based on XML annotations. These files are regular single-line C # comments that include XML tags. They follow the pattern of single-line annotations:

<summary>

This class

</summary>

Multi-line XML annotations follow this pattern:

<exception cref= "Bogusexception" >

This exception gets thrown as soon as a

</exception>

To be considered an XML comment line, all rows must start with three backslashes. The label has the following two categories:

File description Item Format/reference

The first category includes labels like <summary><param>or<exception>. These document descriptions that describe the API elements of a program must be written clearly to facilitate other programmers. As shown in the multiline comment example above, these labels usually have a name

Called or cref property. The compiler examines these properties, so they must be valid and correct. The second class uses a layout such as a <code>,<list>or<para> tag that controls the description of the notes. The file can be generated using the Create menu in the File menu. File

Generated in HTML format:

5. Statement

5.1 Number of declarations per line

It is recommended that there be only one declaration per line, as it makes it easy to annotate

int level;//indentation Level

int size;//size of table

When declaring a variable, do not put multiple variables or variables of different types on the same line, for example:

int A, B; What is ' a '? What's does ' B ' stand for?

The above example also shows a defect with a variable name that is not obvious. Be clear when naming variables.

5.2 Initialization

The local variable is initialized once it is declared. For example:

String name = Myobject.name;

Or

int val = time. Hours;

Note: If you initialize a dialog, the design uses a using statement:

using (OpenFileDialog OpenFileDialog = new OpenFileDialog ()) {

...

}

5.3 Class and interface declarations

When writing C # classes and interfaces, you should follow the following formatting rules:

· Do not use spaces between the method name and the parentheses "(" to begin its argument list.)

· The next line of the declaration statement begins with the curly brace "{" flag.

· Ends with "}" and matches the corresponding start flag by its own indentation.

For example:

Class Mysample:myclass, IMyInterface

{

int myInt;

Public mysample (int myInt)

{

This.myint = myInt;

}

void Inc ()

{

++myint;

}

void Emptymethod ()

{

}

}

Refer to section 10.1 for the position of a curly brace.

6. Statements

6.1 Simple statements

Each line should contain only one statement.

6.2 Return Statement

A return statement does not use the outermost parentheses. No:

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 should be in the following form:

for (int i = 0; i < 5; ++i) {

...

}

or place a line (consider replacing it with a while statement)

for (initialization; condition; update);

The foreach statement should resemble the following:

foreach (int i in intlist) {

...

}

Note: In a loop, even if only one statement is usually enclosed in parentheses.

6.5 while/do-while Statements

A while statement should be written in the following form:

while (condition) {

...

}

An empty while statement should be in the following format:

while (condition);

A do-while statement should be in the following format:

Do

{

...

} while (condition);

6.6 Switch Statement

A switch statement should be in the following format:

Switch (condition) {

Case A:

...

Break

Case B:

...

Break

Default

...

Break

}

6.7 Try-catch Statements

A Try-catch statement statement should follow the following format:

try {

...

} catch (Exception) {}

Or

try {

...

} catch (Exception e) {

...

}

Or

try {

...

} catch (Exception e) {

...

} finally {

...

}

7. Blank

7.1 Blank Line

Empty lines improve readability. They separate blocks of code that are logically related to themselves. Two lines of space should be used between the following:

· A logical segment of a source file.

· Class and interface definitions (each file defines only one class or interface to avoid this).

A space line should always be used between the following:

· Method

· Property

· A local variable in a method and its first statement

· A logical segment of a method in order to improve readability. Note Blank lines must be indented because they include a statement that makes inserting these rows easier.

7.2 Inner Space

A comma or a semicolon should be followed by a space, for example:

TestMethod (A, B, c); Do not use: TestMethod (A,B,C)

Or

TestMethod (A, B, c);

A single space-enclosing operator (except for the unary and logical operators like add), for example:

A = b; Don ' t use a=b;

for (int i = 0; i < ten; ++i)//don ' t use for (int i=0; i<10; ++i)

Or

for (int i=0;i<10;++i)

7.3 Table Formatting

A logical block of rows should be formatted as a table:

String name = "Mr. Ed";

int myvalue = 5;

Test atest = test.testyou;

Formatting a table with spaces instead of tabs because formatting in some tab indents makes the table format look strange.

8. Naming habits

8.1 Uppercase Format

8.1.1 Pascal Casing

Be accustomed to capitalize the first letter of each word (as in testcounter).

8.1.2 Camel Casing

It is customary to capitalize the first letter of each word, such as testcounter, except for the first word.

8.1.3 Full capitalization case

For identifiers consisting of only one or two character abbreviations, the characters is in full capitalization. Identifiers with three or more characters should be replaced by Pascal. For example:

public class Math

{

Public Const PI = ...

Public Const E = ...

Public Const Feigenbaumnumber = ...

}

8.2. Naming guidelines

It is generally considered a bad habit to use low-line characters in the name and naming of Hungarian symbols according to the guidelines.

The Hungarian symbol is a set of prefixes and suffixes that are applied to the naming to map variable types. This naming style is widely used in early Windows programs, but is now canceled at least not advocated. If you follow this guide with the Hungarian notation is not allowed.

But remember that a good variable name describes the semantics without losing the type.

One exception to this rule is the GUI code. Including GUI elements like Buttons (Buttton), all realms and variable names should be prefixed with their type names instead of abbreviations. For example:

System.Windows.Forms.Button CancelButton;

System.Windows.Forms.TextBox nameTextBox;

8.2.1 Class Naming guidelines

· Class naming must be a noun or noun phrase.

· Usepascal Case Reference 8.1.1

· Do not use any class prefixes

8.2.2 Interface Naming Guidelines guidelines

· To name an interface with a noun or noun phrase or adjective that can describe the behavior. (e.g. IComponent or ienumberable)

· Using Pascal case (refer to 8.1.1)

· Prefix with I as the name, it should be followed by an uppercase letter (the first letter of the interface name)

8.2.3 Enumeration Naming guidelines

· Name enumeration value names and type names in Pascal case

· Enum type and enumeration value do not prefix

· For enumerations with a single name

· For bit fields with plural names

8.2.4 read-only and constant naming

· To name a static field with a noun, noun phrase, or noun abbreviation.

· Using Pascal case (ref. 8.1.1)

8.2.5 parameter/very field naming

· Be sure to use descriptive names, which should be sufficient to represent the meaning of the variable and its type. But a good name should be based on the meaning of the parameter.

· Use camel case (refer to 8.1.2)

8.2.6 variable Name

· The count variable is more appropriate to be called I, J, K, L, M, n when used in trivial counting loops. (Refer to 10.2 For example, more intelligent naming of global counts, etc.)-

· Use camel case (refer to 8.1.2)

8.2.7 method naming

· Use a verb or verb phrase to name a method.

· Using Pascal (refer to 8.1.2)

8.2.8 Property Naming

· To name a property with a noun or noun phrase

· Using Pascal case (ref. 8.1.2)

· Consider naming an attribute with the same name as its type

8.2.9 Event naming

· Naming event handlers with event processor suffixes

· Name two parameters with sender and E

· Using Pascal case (ref. 8.1.1)

· Naming event arguments with the EventArgs suffix

· Name the event with a prefix and a copy concept with the current and past tense.

· Consider naming events with 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 Habits

9.1 Visibility

Do not have any public instances or class variables that make them private. For private members It is best not to write "private" as a modifier. Private is the default, and every C # programmer should be aware of it.

Use attributes instead. You can use a public static (or constant) for this rule to be with an exception, taking it should not be a rule.

9.2 No "magic" number

Do not use the magic number, that is, in the source code directly with the constant value. Instead of these latter in case of change (say, your application can handle 3540 users instead of 427 your code in 50 lines by dispersing 25000LOC) is wrong and no gain. Declare a constant with a number in place of:

public class MyMath

{

Public Const Double PI = 3.14159 ...

}

10. Coding 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 start with a new line after the following conditions:

· namespace declaration (note that this is new in version 0.3 and differs from version 0.2)

· class/interface/struct declaration

· Method declaration

10.2 Example of variable naming

Replace:

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.");

}

}

Note: Index variables are usually called I, J, K, and so on. But note:indexer variables generally should be called I, J, K etc. But in the event of this, it makes more sense to reconsider the principle. In general, when the same counter or indexer is reused, give them meaningful names.

C # code Specification-Programming Secrets

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.