See "C# Advanced Programming, Fourth Edition"
· One reason for writing a static constructor is that a class has some static fields or properties that need to be initialized from an external source before the class is used for the first time.
· Static constructors run at most once, before code references the class.
· The static constructor has no access modifiers and is never called by other C# code, so access modifiers like public and private are meaningless.
· The static constructor cannot take any parameters, and a class can only have one static constructor.
· Static constructors can only access static members of the class, not instance members.
An example is given below:
public class UserPreferences
{
public static readonly Color BackColor;
static UserPreferences()
{
//read BackColor from out source;
}
// ...
}
classMainEntryPoint
{
static void Main()
{
Console.WriteLine(UserPreferences.BackColor.ToString());
}
}
Note that parameterless instance constructors can safely coexist with static constructors in a class. Although the parameter list is the same, there is no contradiction, because the static constructor is executed when the class is loaded, and the instance constructor is executed when the instance is created, so there will be no conflict in the execution of the constructor.
class MyTempClass
{
public static int num = 100;
static MyTempClass()
{
num = 101;
}
}
class Program
{
static void Main(string[] args)
{
int x = MyTempClass.num;
Console.WriteLine();
}
}
In the above program, if the static constructor is not added, the value of x is 100. With the constructor added, the value of x is 101.