Item13: Initialize static class members with static constructiors
We know that static member variables should be initialized before all types of instances are created. C # Let's use static initialization and static constructor for this purpose. A static constructor is a special function that runs before all methods, member variables, or attribute definitions in the class. We use this method to declare static variables in the class to construct the singleton design pattern or other required work. We should not use the default constructor, some special private functions or other methods for declaring static variables.
Just like instance initialization, we can use static constructors to declare static member variables. If you only need simple static member variables, you can use the initialization method. If we need to use more complex logic, we need to use the constructors of static member variables to create them.
In the involved mode of C #, the singleton mode is frequently used. We only need to set the class instantiation constructor to private, and then add the initialization of static members:
Public class mysingleton
{
Private Static readonly mysingleton _ theoneandonly = new mysingleton ();
Public static mysingleton theonly
{
Get
{
Return _ theoneandonly;
}
}
Private mysingleton ()
{
}
}
The Singleton mode can be achieved simply by using the following methods.
Public class mysingleton
{
Private Static readonly mysingleton _ theoneandonly;
Static mysingleton ()
{
_ Theoneandonly = new mysingleton ();
}
Public static mysingleton theonly
{
Get
{
Return _ theoneandonly;
}
}
Private mysingleton ()
{
}
}
Like instance initialization, static member variable Initialization is executed before the static constructor is called.
When our application loads our type for the first time, the CLR will call our static constructor. We can only define one static constructor, and it cannot have parameters. Because the static constructor is called by CLR, we must be careful that it may cause exceptions. Once an exception exists, CLR will abort our program. We do not initialize static variables directly, but use static constructors because of this. Through static constructor, we can easily capture these exceptions.
Static mysingleton ()
{
Try
{
_ Theoneandonly = new mysingleton ();
}
Catch
{
// Capture exceptions
}
}
Static initialization and static constructor provide a cleaner and easier way to declare static members of our type. They are easier to understand and debug.
Translated from Objective C #: 50 specific ways to improve your C # by Bill Wagner
Back to directory