C # Coding specifications

Source: Internet
Author: User

C #Code Specification

1.Avoid placing multiple classes in one file.

2.A file must have only one namespace, so that you do not need to put multiple namespaces in the same file.

3.A file should not exceed500RowCode(Not includingIDEGenerated code ).

4.The code length of a method should not exceed25Line.

5.Avoid exceeding5Parameters. If this parameter is exceeded, useStructTo pass multiple parameters.

6.Each line of code should not exceed80Characters.

7.In principle, tryDo not manually modify the code generated by the machine.

A)To edit a machine (IDEThe format and style of the generated code must comply with the encoding standard.

B)Use the fragment class as much as possible to break down the maintained part into various factors.

Note: The translation here refers to the old man of inspiration.Visual C #2005Medium,C #The syntax of is supported.PartialModifier, which is used to break down a complete class into various classes. during compilation, the compiler constructs them into a class.

For more information, see

Http://weblogs.asp.net/jaybaz_ms/archive/2004/04/28/122392.aspx

8.Avoid using annotations to explain obvious code.

A)The Code should be self-explanatory. Good Code itself should be well readable. the variables and methods used for naming generally do not need to be annotated.

9.The document should only be usedAssumptions, algorithm insights, etc.

10.Avoid using method-level documents.

A)Use extendedAPIDocumentation.

B)Method-level annotations are used only when the method needs to be used by other developers. (InC #Moderate///)

11.Do not hard-encode the value of a number. Always use the constructor to set its value.

12.Only a natural structure can be used directlyConst (Constant)For example, the number of days in a week.

13.The usage of read-only variables and constants is different,To implement Read-Only variables, you can directly useReadonlyModifier.

Public class myclass

{

Public readonly int number;

Public myclass (INT somevalue)

{

Number = somevalue;

}

Public const int daysinweek = 7;

}

14.Each hypothesis must useAssertCheck

A)Average per15The row must be checked once.(Assert)

Using system. diagnostics;

 Object GetObject ()

{...}

 Object OBJ = GetObject ();

Debug. Assert (OBJ! = NULL );

15.Each line of the Code should be tested in white box mode.

16.Only exceptions that have been displayed and processed are thrown.

17.In the capture(Catch)Clause that throws an exception(Throw)Always throws the original exception to maintain the stack allocation of the original error.
Catch (exception)

{

 MessageBox. Show (exception. Message );

Throw ;//AndThrow exceptionSame.

}

Note: Likewise, direct return operations are not recommended in loop statements.
For (INT I = 0; I <100; I ++)
{
If (I = 10)
{
Return; // not recommended
}
}

18.The returned value of the method is the error code.

19.Avoid defining custom exception classes as much as possible.

20.When a custom exception needs to be defined:

A)Custom exceptions must be inherited fromApplicationexception.

B)Provides custom serialization functions.

21.AvoidProgramUse multipleMainMethod.

22.Only the necessary operations are published.Internal.

23.Avoid using a friend Assembly because it increases the coupling between the Assembly.

24.Avoid writing code for the Assembly loaded from the specified position.

25.Minimize application assembly code(ExeCustomer Program). Use a class library to replace the included business logic.

26.Avoid providing explicit values for enumeration variables.

//Correct Method 

Public Enum color

{

Red, green, blue

}

//Avoid

Public Enum color

{

Red = 1, Green = 2, Blue = 3

}

27.Avoid specifying special enumerated variables.

//Avoid 

Public Enum color: Long

{

Red, green, blue

}

28.Even ifIfThe statement has only one sentence.IfThe statement content is expanded in braces.

29.Avoid usingTrinaryConditional operators.

30.Avoid returning in a Condition StatementBoolValue Function. You can use local variables and check these local variables.

Bool iseverythingok ()

{...}

//Avoid

If (iseverythingok ())

{...}

//Replacement Scheme 

Bool OK = iseverythingok ();

If (OK)

{...}

31.Always use based on0Array.

32.In a loop, arrays of reference types are always explicitly initialized.

Public class myclass

{}

Myclass [] array = new myclass [2, 100];

For (INT Index = 0; index <array. length; index ++)

{

Array [Index] = new myclass ();

}

33.TryDo not providePublicAndProtectedTo replace them with attributes.

34.Avoid using in inheritanceNewAnd useOverrideReplace.

35.InSealedInPublicAndProtectedMarkVirtual.

36.Unless you useInterOP (COM +Or otherDLL)Otherwise, do not use Insecure code.(Unsafe code).

37.Avoid Explicit conversions and useAsOperator to convert compatible types.

Dog dog = new germanshepherd ();

Germanshepherd Shepherd = dog as germanshepherd;

If (Shepherd! = NULL)

{...}

38.When class members include Delegation

A)Before calling a delegate, copy it to a local variable to avoid concurrent contention conditions.

B)Before calling a delegate, check whether it isNull

Public class mysource

{

Public event eventhandler myevent;

Public void fireevent ()

{
// Copy the delegate to a local variable.
Eventhandler temp = myevent;

// Determine whether it is empty
 If (temp! = NULL)

{

Temp (this, eventargs. Empty );

}

}

}

39.Do not provide public event member variables. Use the event accessors to replace these variables.

Public class mysource

{

Mydelegate m_someevent;

Public event mydelegate someevent

{

Add

{

M_someevent + = value;

}

Remove

{

M_someevent-= value;

}

}

}

40.Use an event help class to publish the definition of an event.

41.Always use interfaces.

42.Methods and attributes in classes and interfaces must be at least2:1.

43.Avoid having only one member in an interface.

44.Try to include3-5Members.

45.The member in the interface should not exceed20.

A)AccordingThe actual situation may be limited12Items

46.Avoid adding events to interface members.

47.Avoid using abstract methods instead of using interfaces.

48.Display Interfaces in the class hierarchy.

49.Explicit interfaces are recommended.

50.It is never assumed that a type is compatible with one interface, and the interfaces should be prevented from being queried.

Sometype obj1;

Imyinterface obj2;

 

/*Assume that the existing code has been initialized.Obj1Next*/

Obj2 = obj1 as imyinterface;

If (obj2! = NULL)

{

Obj2.method1 ();

}

Else

{

//Handling error

}


51.The string displayed to the end user (generally part of the UI Interface) should not be directly encoded, but should be replaced by a resource file.

 Note: The purpose of this operation is to facilitate software localization.


52.Do not directly write configuration-based strings that may be changed, such as connection strings.


53.When you need to build a long string, consider usingStringbuilderDo not useString.

Note:StringEach time you create a new instance, it occupies a lot of space and produces a relativeStringbuilderHigher Performance consumption. For string operations that are too frequent, useStringbuilderIs a good habit.


54.Avoid providing methods in the structure.

A)Parameterized constructors are recommended.

B)Reload Operators


55.Always provide static constructors for static variables.


56.InIn the case of early binding, try to avoid late binding.

Note: later binding is flexible, but not only brings about performance consumption, but also complexity and chaotic logic in coding.

57.Use application logs and tracing.


58.Unless in an incompleteSwitchStatement. Otherwise, do not useGotoStatement.

Note: should not be used in principleGotoStatement, unless it can greatly reduce the complexity of the encoding and does not affect readability.


59.InSwitchThere must always beDefaultClause to display information(Assert).

Int number = somemethod ();

Switch (number)

{

Case 1:

Trace. writeline ("Case 1 :");

Break;

Case 2:

Trace. writeline ("Case 2 :");

Break;

Default:

Debug. Assert (false );

Break;

}

60.Do not useThisPointer.

//Correct useThisExample

Public class myclass

{

Public myclass (string message)

{}

Public myclass (): This ("hello ")

{}

}

61.Do not useBaseTo access the members of the base class.

//Correct useBaseExample

Public class dog

{

Public dog (string name)

{}

Virtual public void bark (INT Howlong)

{}

}

Public class germanshepherd: Dog

{

Public germanshe pherd (string name): Base (name)

{}

Override public void bark (INT Howlong)

{

Base. Bark (Howlong );

}

}

62.To implement the template-basedDispose ()AndFinalize ()Two methods.

63.GenerallySystem. ObjectConversion and conversionSystem. ObjectUse the forced conversion orAsOperator replacement.

Class someclass

{}

//Avoid:

Class myclass <t>

{

Void somemethod (T)

{

Object temp = T;

Someclass OBJ = (someclass) temp;

}

}

//Correct:

Class myclass <t> where T: someclass

{

Void somemethod (T)

{

Someclass OBJ = T;

}

}

64.In general, do not define interfaces with delimiters. The restriction level of an interface can be replaced by a strong type.

Public Class Customer

{...}

//Avoid:

Public interface ilist <t> where T: customer

{...}

//Correct:

Public interface icustomerlist: ilist <customer>

{...}

65.You are not sure about the restrictions of specific methods in the interface.

66.Always choose to useC #Built-in (GeneralGenerics) Data Structure

67. Do not assign a null value to an instance of the class unless necessary.
68. Do not assign a value to the referenced instance and assign it to NUL, especially the class member l modified by public.
1) if the instance is a temporary reference, use the using statement and use it in the program block.
2) if you need to release resources, you should probably use dispose and use the null value method. This reference will not be recycled until it points to the next instance.

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.