Before creating any instance of the type, we need to initialize the static member variable of this type. C # can complete this task through the static initialization or static constructor, the static constructor is a special function that is executed before any methods of a class, changes to zero, or attributes are accessed.
We should not use the type example constructor or some non-static methods in the type to initialize static member variables of the type.
If the initialization process of static members is not complex, we can initialize them in the initialization tool of the type. If static members need to perform a lot of logical operations during initialization, then we can extract the initialization process to the static constructor.
We can use a static constructor to implement the singleton mode in the design mode, as shown in the following code.
Code
1 public class MySingleton
2 {
3 private static readonly MySingleton _theOneAndOnly =
4 new MySingleton( );
5
6 public static MySingleton TheOnly
7 {
8 get
9 {
10 return _theOneAndOnly;
11 }
12 }
13
14 private MySingleton( )
15 {
16 }
17
18 // remainder elided
19 }
Similar to the example initializer, the static initiator runs before the explicit code in the static constructor. Similarly, the static constructor also runs before the static constructor of the base class.
Static initializes and constructors provide the clearest Initialization Method for static members of our type. Using this method, the code is both easy to read and error prone. C # uses them to solve the problem of static member initialization in other languages.