SoFunction
Updated on 2025-03-08

C# coding is a good habit, dedicated to all comrades who love C#

1. Avoid placing multiple classes in one file.
2. A file should have only one namespace, so avoid placing multiple namespaces in the same file.
3. It is best not to have more than 500 lines of code in a file (excluding machine-generated code).
4. It is best not to exceed 25 lines of code length for a method.
5. Avoid the situation where there are more than 5 parameters in the method. Use structures 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 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.
8. Avoid using comments to explain obvious code.
a) The code should be self-interpreting. Good code is named by readable variables and methods so no comment is required.
9. Document only operational assumptions, algorithm insights and so on.
10. Avoid using method-level documents.
a) Use the extended API documentation to describe it.
b) Method-level annotations are used only when this method needs to be used by other developers. (In C#, it is ///)
11. Do not hardcode the value of a number, always use the constructor to set its value.
12. Const can be used directly only if it is a natural structure, such as the number of days in a week.
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 be checked using Assert
a) On average, there must be a check for every 15 rows (Assert)
using ;
object GetObject()
{…}
object obj = GetObject();
(obj != null);
15. Every line of the code should be tested in a white box manner.
16. Only exceptions that have been displayed are thrown.
17. In the throw exception clause of the catch statement (throw), the original exception is always thrown to maintain the stack allocation of the original error.
catch(Exception exception)
{
();
throw ; //Same as throw exception.
}
18. The return value of the avoidance 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 must be inherited from ApplicationException.
b) Provide customized serialization functions.
21. Avoid using multiple Main methods in a single assembly.
22. Only necessary operations are announced to the public, while others are internal.
23. Avoid friend assemblies, as it increases inter-assembly coupling.
24. Avoid code that relies on an assembly running from a particular location.
25. Make the application set minimize code (EXE client program). Use the class library to replace the included business logic.
26. Avoid providing explicit values ​​to enum variables.
//The correct method
public enum Color
{
Red,Green,Blue
}
//avoid
public enum Color
{
Red = 1,Green = 2,Blue = 3
}
27. Avoid specifying special types of enum variables.
//avoid
public enum Color : long
{
Red,Green,Blue
}
28. Even if there is only one sentence in the if statement, the content of the if statement should be extended in braces.
29. Avoid using trinary condition operators.
30. Avoid calling functions that return bool values ​​in conditional statements. You can use local variables and check them.
bool IsEverythingOK()
{…}
//avoid
if (IsEverythingOK ())
{…}
//Replacement
bool ok = IsEverythingOK();
if (ok)
{…}
31. Always use an array starting from 0.
32. Always explicitly initialize an array of reference types in a loop.
public class MyClass
{}
MyClass[] array = new MyClass[100];
for(int index = 0; index < ; 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 using override replacement.
35. In classes that are not sealed, the methods of public and protected are always marked as virtual.
36. Do not use unsafe code unless you use interop(COM+ or other dll) code.
37. Avoid display conversions and use the as operator to perform conversions of compatible types.
Dog dog = new GermanShepherd();
GermanShepherd shepherd = dog as GermanShepherd;
if (shepherd != null )
{…}
38. When class members include delegations
a) Copy a delegate to a local variable before publishing to avoid concurrency race
condition.
b) Be sure to check if 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,);
}
}
}
39. Do not provide public event member variables, replace them with 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 interface.
42. Methods and properties in classes and interfaces are at least 2:1 ratio.
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 including events in interface members.
47. Avoid using abstract methods and using interface replacement.
48. Display interfaces in 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 that the code has initialized obj1, next */
obj2 = obj1 as IMyInterface;
if (obj2 != null)
{
obj2.Method1();
}
else
{
//Processing error
}
51. Do not use hard-coded strings to end users but replace them with resource files.
52. Do not hard-code configuration-based strings that may be changed, such as connection strings.
53. When you need to build a long string, use StringBuilder instead of string
54. Avoid providing methods in structures.
a) It is recommended to use parameterized constructors
b) Operators can be retried
55. Always provide static constructors to static variables.
56. If you can use early binding, do not use late binding.
57. Use the application's logs and tracking.
58. Do not use goto statements unless incomplete switch statements.
59. There must always be a default clause in the switch statement to display information (Assert).
int number = SomeMethod();
switch(number)
{
case 1:
("Case 1:");
break;
case 2:
("Case 2:");
break;
default :
(false);
break;
}
60. Do not use this pointer unless other constructors are called 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 the base class members unless you want to override a member with a name conflict in the subclass or call the constructor of the base class.
// Example of correct 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. When based on templates, you must implement the two methods Dispose() and Finalize().
63. Usually avoid codes that come from and from conversions, and use cast or as operator replacement.
class SomeClass
{}
//avoid:
class MyClass <T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
// correct:
class MyClass <T> where T : SomeClass
{
void SomeMethod(T t)
{
SomeClass obj = t;
}
}
64. Under normal circumstances, do not fix interfaces with restrictors. The restriction level of an interface can usually be replaced by a strong type.
public class Customer
{…}
//avoid:
public interface IList <T> where T : Customer
{…}
//correct:
public interface ICustomerList : IList <Customer>
{…}
65. Uncertain the limitations of specific methods within the interface.
66. Always choose to use C# built-in (generics) data structures.