C # Coding Good habits, dedicated to all students who love C #

Source: Internet
Author: User

1. Avoid placing multiple classes in a file.

2. A file should have only one namespace, avoiding the need to place multiple namespaces in the same file.

3. A file should preferably not exceed 500 lines of code (excluding machine-generated code).

4. The code length of one method should not be more than 25 lines.

5. Avoid cases where there are more than 5 parameters in a method. Use structs to pass multiple parameters.

6. Do not exceed 80 characters per line of code.

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

A) If you need to edit the machine-generated code, edit the format and style to conform to that coding standard.

b) Use partial classes whenever possible to factor out the maintained portions.

8. Avoid using annotations to explain the obvious code.

A) The code should be self-explanatory. Good code is named by a readable variable and method, so no comment is required.

9. Document only operational assumptions, algorithm insights and so on.

10. Avoid using the method-level documentation.

A) Use the Extended API documentation to describe it.

b) Use method-level annotations only when the method needs to be used by other developers. (in C # is///)

11. Do not hardcode the value of a number, always use the constructor to set its value.

12. Only natural structures are used to directly use const, such as one weeks of days.

13. Avoid using const on read-only variables. If you want to implement read-only, you can use ReadOnly directly.

public class MyClass

{

public readonly int number;

Public MyClass (int somevalue)

{

Number = Somevalue;

}

public const int Daysinweek = 7;

}

14. Each hypothesis must use an Assert check

A) an average of one check (Assert) per 15 lines

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. Throws only the exception that has been displayed for processing.

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

catch (Exception Exception)

{

MessageBox.Show (Exception. Message);

throw; Same as the throw exception.

}

18. Avoid the return value of the method is the error code.

19. Try to avoid defining custom exception classes.

20. When you need to define a custom exception:

A) custom exceptions are inherited from ApplicationException.

b) provides a custom serialization feature.

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

22. Only the necessary operations are disclosed, others are internal.

Avoid friend assemblies, as it increases inter-assembly coupling.

Avoid code that relies in an assembly running from a particular location.

25. Make the application set as minimal code (EXE client) as possible. Use the class library to replace the included business logic.

26. Avoid providing an explicit value to the enumeration variable.

Correct method

public enum Color

{

Red,green,blue

}

Avoid

public enum Color

{

Red = 1,green = 2,blue = 3

}

27. Avoid specifying enumeration variables of a particular type.

Avoid

public enum Color:long

{

Red,green,blue

}

28. Even if the IF statement has only one sentence, the contents of the If statement should be expanded with curly braces.

29. Avoid using the trinary condition operator.

30. Avoid calling functions that return bool values in a conditional statement. You can use local variables and examine these local variables.

BOOL Iseverythingok ()

{...}

Avoid

if (Iseverythingok ())

{...}

Replacement scenarios

bool OK = Iseverythingok ();

if (OK)

{...}

31. Always use a 0-based array.

32. An array of reference types 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 member variables for public and protected, use attributes instead of them.

34. Avoid using the override substitution with new in inheritance.

35. The public and protected methods are always marked as virtual in classes that are not sealed.

36. Do not use unsafe code unless you are using Interop (COM + or other DLL) code.

37. Avoid the display of conversions, using the AS operator for compatible type conversions.

Dog dog = new Germanshepherd ();

Germanshepherd Shepherd = Dog as Germanshepherd;

if (Shepherd! = null)

{...}

38. When a class member includes a delegate

A) Copy a delegate to a local variable before publishing to avoid concurrency race

Condition.

b) Be sure to check whether it is null before invoking the delegate

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, and use 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 helper class to advertise the definition of the event.

41. Always use the interface.

42. Methods and properties in classes and interfaces are at least proportional to 2:1.

43. Avoid having only one member in an interface.

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

45. There should be no more than 20 members in the interface.

A) The actual situation may be limited to 12

46. Avoid the inclusion of events in the interface members.

47. Avoid using an abstract method and use interface substitution.

48. Display the interface in the class hierarchy.

49. It is recommended to use an explicit interface implementation.

50. Never assume that a type is compatible with an interface. Defensively query for that interface.

SomeType obj1;

IMyInterface Obj2;


/* Assuming the code has been initialized over obj1, then */

Obj2 = obj1 as IMyInterface;

if (obj2! = null)

{

Obj2. Method1 ();

}

Else

{

Handling Errors

}

51. Do not use hard-coded strings for the end user to replace them with resource files.

52. Do not HardCode configuration-based strings that may change, such as connection strings.

53. When you need to build a long string, use StringBuilder not to use string

54. Avoid providing methods within the structure.

A) the use of parameterized constructors is recommended

b) You can re-crop the operator

55. Always provide static constructors for static variables.

56. Do not use late binding when you can use early binding.

57. Use the application's logs and traces.

58. Do not use a goto statement unless you are in an incomplete switch statement.

59. Always have the default clause in the switch statement to display the 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 the this pointer unless you call other constructors in the constructor.

Example of using this correctly

public class MyClass

{

Public MyClass (String message)

{}

Public MyClass (): This ("Hello")

{}

}

61. Do not use base to access members of the base class unless you want to override a member of a name conflict in a subclass or call the constructor of the base class.

Example of using base correctly

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 Dispose () and Finalize () two methods based on the template.

63. In general, avoid the code that is converted from System.Object and converted by System.Object, and replaced with a cast or as operator.

Class SomeClass

{}

Avoid:

Class MyClass <T>

{

void SomeMethod (T t)

{

Object temp = t;

SomeClass obj = (someclass) temp;

}

}

That's right:

Class MyClass <T> where T:someclass

{

void SomeMethod (T t)

{

SomeClass obj = t;

}

}

64. In general, do not fuser the interface with the limiter. The limit level of an interface can usually be replaced with a strong type.

public class Customer

{...}

Avoid:

public interface IList <T> where T:customer

{...}

That's right:

public interface Icustomerlist:ilist <Customer>

{...}

65. The limitations of specific methods within the interface are not determined.

66. Always choose to use C # built-in (general generics) data structures.

Http://www.cnblogs.com/zhangronghua/archive/2006/12/20/598386.html

C # Coding Good habits, dedicated to all students who love C #

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.