C #66 encoding standards

Source: Internet
Author: User
Tags coding standards

Http://www.educity.cn/develop/1389490.html

C #66 encoding standards

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 contain no more than 500 lines of code (excluding the code generated by the machine ).

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

5. Avoid more than five parameters in the method. Use the structure to pass multiple parameters.

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

7. Do not manually modify the code generated by the machine.

A) if you need to edit the code generated by the machine, the editing format and style must comply with the encoding standard.

B) use partial classes whenever possible to factor out the maintained portions. Try to use partial classification factors for maintenance.

8. Avoid using annotations to explain obvious code.

A) the code should be self-explanatory. Good code is named by readable variables and methods, so no comments are required.

9. document only operational assumptions, algorithm insights and so on. ---- documents only operate on assumptions, algorithm insights, and so on.

10. Avoid using method-level documents.

A) instructions on using the extended API documentation.

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 be used directly, such as the number of days in a week.

13. Avoid using const on read-only variables. To implement read-only, you can directly use readonly.


  
  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 the catch statement, 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.

}

18. Avoiding the return 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 friend assemblies, as it increases inter-assembly coupling. -- avoid friend Assembly because it increases inter-assembly coupling.

24. Avoid code that relies on an assembly running from a participant location. -- avoid code dependency on an assembly running from a specific location.

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[100];   
   
  for(int index = 0; index <  array.Length;  index++)   
   
  {   
   
     array[index] = new  MyClass();   
   
  }   
   

33. do not provide public and protected member variables. 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. To avoid display conversions, 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) copy a delegate to a local variable before publishing to avoid concurrency race

Condition.

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


  
  public class MySource   
   
  {   
   
     public event EventHandler  MyEvent;   
   
     public void FireEvent()   
   
     {   
   
        EventHandler temp = MyEvent;   
   
        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 situation may be limited to 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 an interface. Defensively query for that interface.

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 end users should not be hard-coded but should be replaced with resource files.

52. Do not hard encode configuration-based strings that may be modified, such as connection strings.

53. Use stringbuilder instead of string to build long strings.

54. Avoid providing methods in the structure.

A) parameterized constructors are recommended.

B) operators that can be retained

55. Always provide static constructors for static variables.

56. Do not use post-binding if you can use early binding.

57. Use application logs and tracing.

58. Do not use the GOTO statement unless in an incomplete switch statement.

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. In general, do not set an interface with a separator. 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 C # built-in (General generics) data structure.

The above are the 66 C # coding standards summarized.

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.