The static constructor can be used in C # to initialize class data in the same way as the instance constructor used to initialize instance data. There are some differences between static constructor and instance constructor rules. Unlike the instance constructor, static constructor cannot be overloaded, so only one default non-parameter static constructor is available for static constructor. Static constructors cannot be explicitly called or inherited from the derived class, but can be called when a base class type is created.
C # principles for using static constructor:
1. The static constructor is called before the class instance is created. Therefore, it is called before all instance constructor instances.
2. The static constructor is called before the first instance of the class is created.
3. The static constructor is called before a static field is referenced.
The following is a simple example. Class Test
{
Static Test ()
{
Console. writeline ("");
}
Public test ()
{
Console. writeline ("B ");
}
}
Class test1: Test
{
Public test1 ()
{
Console. writeline ("C ");
}
}
Test T = new test () during instantiation ();
Test T1 = new test ();
Test1 t2 = new test1 ();
Output: A, B, B, B, c
The static constructor is called only once.