A c # programming specification on the Internet

Source: Internet
Author: User

1. Avoid placing multiple classes in one file.

2. A file should have only one namespace. Avoid placing multiple namespaces in the same file.

3. A file should have no more than 500 lines of code (excluding the code produced by IDE ).

4. The code length of a method should not exceed 25 lines.

5. Avoid more than five parameters in the method. If this parameter is exceeded, use struct to pass multiple parameters.

6. Each line of code should not exceed 80 characters.

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

A) if you need to edit the code generated by the machine (IDE), the editing format and style 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 idea source man's statement. in Visual C #2005, the C # syntax already supports the partial modifier, it is used to break down a complete class into different classes. during compilation, the compiler constructs them into a class.

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 used for assumptions, algorithm insights, and so on.

10. Avoid using method-level documents.

A) use the extended API documentation for instructions.

B) method-level annotations are used only when the method needs to be used by other developers. (In C #, It is ///)

11. Do not hard encode the numeric value. Always use the constructor to set its value.

12. Only a natural structure can directly use const (constant), such as 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 use the readonly modifier.

Public class myclass

{

Public readonly int number;

Public myclass (INT somevalue)

{

Number = somevalue;

}

Public const int daysinweek = 7;

}

14. Each hypothesis must use assert check

A) An average check (assert) is required for every 15 rows)

Using system. diagnostics;

Object GetObject ()

{...}

Object OBJ = GetObject ();

Debug. Assert (OBJ! = NULL );

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

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

17. In the throw clause of catch statements, the original exception is always thrown to maintain the stack allocation of the original error. Catch (exception)

{

MessageBox. Show (exception. Message );

Throw; // The same as throw exception.

}

Note: Likewise, direct return operations are not recommended in loop statements. For (INT I = 0; I <100; I ++) {if (I = 10) {return; // not recommended method} 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 inherit from applicationexception.

B) provides custom serialization functions.

21. Avoid using multiple main methods in a single set.

22. Only the necessary operations are published, and the others are 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 the application assembly code (exe client 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 if the if statement contains only one sentence, the content of the IF statement should be expanded with braces.

29. Avoid using the trinary conditional operator.

30. Avoid calling the function that returns the bool value in the Condition Statement. 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 an array starting from 0.

32. The array of reference type is always explicitly initialized in the loop.

Public class myclass

{}

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

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

{

Array [Index] = new myclass ();

}

33. do not provide public and protected member variables as much as possible, and use attributes instead of them.

34. Avoid replacing override with new in inheritance.

35. In a class other than sealed, the public and protected methods are always marked as virtual.

36. Do not use unsafe code unless InterOP (COM + or other DLL) code is used ).

37. Avoid Explicit conversions and use the as operator 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 the delegate, copy it to a local variable to avoid concurrent contention conditions.

B) Check whether the delegate is null before calling it.

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. replace these variables with the event accessors.

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. The ratio of methods and attributes in classes and interfaces should be at least.

43. Avoid having only one member in an interface.

44. Try to make each interface contain 3-5 members.

45. The number of interface members should not exceed 20.

A. The actual number may be 12.

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 those interfaces should be queried.

Sometype obj1;

Imyinterface obj2;

/* Assume that the existing code has initialized obj1, and then */

Obj2 = obj1 as imyinterface;

If (obj2! = NULL)

{

Obj2.method1 ();

}

Else

{

// Handle errors

}

51. Strings displayed to the end user (generally part of the UI Interface) should be replaced by resource files instead of directly encoded.

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 using stringbuilder not to use string for processing.

Note: each time a new instance is created for a string, it consumes more space and consumes more performance than stringbuilder. It is a good habit to use stringbuilder for character string operations that are too frequent.

54. Avoid providing methods in the structure.

A) parameterized constructors are recommended.

B) Reload operators.

55. Always provide static constructors for static variables.

56. When early binding is available, try to avoid later 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. Do not use the GOTO statement unless in an incomplete switch statement.

Note: In principle, the GOTO statement should not be used unless it can greatly reduce the complexity of the encoding and does not affect readability.

59. In the switch statement, there must always be a default clause 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 use this pointer unless other constructors are called in the constructor.

// Example of correct use of this

Public class myclass

{

Public myclass (string message)

{}

Public myclass (): This ("hello ")

{}

}

61. Unless you want to override a member with conflicting names in the subclass or call the base class constructor, do not use base to access the base class members.

// Example of correct base usage

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. Implement the dispose () and finalize () methods when using templates.

63. In general, do not convert code from system. Object To system. object, but use forced conversion or as operator 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. Generally, 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 use the data structure 67 built-in (General generics) of C #. Do not assign a null value unless necessary during class initialization. 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.

 

The specification should be taken into consideration, but it is not necessary to take full care of it.

It is important to know what the purpose of the establishment of each regulation is and where it is applicable.
The reason for becoming a standard is that many people use it, at least because it indicates that the standard has its advantages. However, everything is not absolute. In different application scenarios and objective conditions, "advantages" sometimes become a stumbling block. Therefore, how to apply specifications depends on the actual situation. Believe that your boss can
1. readable code
2. Code with poor readability but High Efficiency
The above two make a wise choice.

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.