C # Coding Good habits, dedicated to all love C # comrade _c# Tutorial

Source: Internet
Author: User
Tags assert throw exception
1. Avoid putting multiple classes in one file.
2. A file should have only one namespace and avoid placing multiple namespaces in the same file.
3. A file is best not to exceed 500 lines of code (excluding machine generated code).
4. The code length of a method is best not to exceed 25 lines.
5. Avoid cases where there are more than 5 parameters in the method. Use structs to pass multiple parameters.
6. Do not exceed 80 characters per line of code.
7. Do not manually modify the machine generated code.
A If you need to edit the machine-generated code, edit the format and style to conform to the coding standard.
b) Use partial classes whenever possible to factor out the maintained portions.
8. Avoid using annotations to explain obvious code.
A the code should be self explanatory. Good code is named after readable variables and methods, so no annotations are required.
9. Document only operational assumptions, algorithm insights and.
10. Avoid using method-level documents.
(a) Use the Extended API documentation to describe it.
b) Use method-level annotations only if the method needs to be used by other developers. (in C # is///)
11. Do not hard-code the value of a number, always use the constructor to set its value.
12. Only natural structures can be used directly, such as days of one weeks.
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 assumption must use an Assert check
A) an average of one check per 15 lines (Assert)
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. Throws only the exception that has been displayed for processing.
17. In the throw exception clause of a capture (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; The same as throw exception.
}
18. Avoid the return value of the method is an error code.
19. Avoid defining custom exception classes as much as possible.
20. When you need to define a custom exception:
A custom exception to inherit from ApplicationException.
b provides custom serialization functionality.
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 is relies on the assembly running from particular location.
25. Make the application set to minimize code (EXE client program). Use the class library to replace the included business logic.
26. Avoid providing an explicit value to an enumeration variable.
The right way
public enum Color
{
Red,green,blue
}
Avoid
public enum Color
{
Red = 1,green = 2,blue = 3
}
27. Avoid specifying special types of enumeration variables.
Avoid
public enum Color:long
{
Red,green,blue
}
28. Even if the IF statement is only one sentence, the contents of the IF statement are expanded with curly braces.
29. Avoid using the trinary condition operator.
30. Avoid calling a function that returns a bool value 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 an array based on the 0 start.
32. An array of reference types that are always explicitly initialized in loops.
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 using new in inheritance and replace with override.
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 use Interop (COM + or other DLL) code (unsafe).
37. Avoid the display of the conversion, using the AS operator for compatible type conversion.
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
Condition.
b Be sure to check that it is null before calling 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 Help class to advertise the definition of the event.
41. Always use an interface.
42. The methods and properties in the class and interface are at least 2:1 proportional.
43. Avoid having only one member in an interface.
44. Maximize the inclusion of 3-5 members in each interface.
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 interface members.
47. Avoid using abstract methods instead of using interface substitution.
48. Display interfaces 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;
/* Assume that the code has initialized the OBJ1, and then * *
Obj2 = obj1 as IMyInterface;
if (obj2!= null)
{
Obj2. Method1 ();
}
Else
{
Handling Errors
}
51. The string that is displayed to the end user should not be hard-coded and replaced with a resource file.
52. Do not hard-code a configuration-based string, such as a connection string, that may be changed.
53. When you need to build a long string, use StringBuilder not to use string
54. Avoid providing methods within the structure.
A) recommends the use of parameterized constructors
b) can be reset operator
55. Always provide static constructors for static variables.
56. Do not use late binding if you can use early binding.
57. Use the log and trace of the application.
58. Do not use goto statements unless you are in an incomplete switch statement.
59. Always have a 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 another constructor in the constructor.
Examples of proper use of this
public class MyClass
{
Public MyClass (String message)
{}
Public MyClass (): This ("Hello")
{}
}
61. Do not use base to access members of a base class unless you want to override a member of a name conflict in a subclass or call a constructor of a base class.
Examples of proper use of base
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 Dispose () and Finalize () two methods based on the template.
63. Generally avoid having to convert from System.Object to code converted by System.Object, instead of using a cast or as operator.
Class SomeClass
{}
Avoid:
Class MyClass <T>
{
void SomeMethod (t)
{
Object temp = t;
SomeClass obj = (someclass) temp;
}
}
That's right:
Class MyClass <T> where T:someclass
{
void SomeMethod (t)
{
SomeClass obj = t;
}
}
64. In general, do not fuser the interface with a restricted character. 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. Uncertainty over the limitations of specific methods within the interface.
66. Always choose to use C # built-in (general generics) data structure.

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.