We can use a static constructor to initialize any static data.
static constructor can only run once.
We cannot call a static constructor directly.
The static constructor will be called automatically in either of these scenarios:
using System; class A//from w w w.ja va 2 s. c o m { static int StaticCount = 0, InstanceCount = 0; static A() { StaticCount++; Console.WriteLine("Static constructor.Count={0}", StaticCount); } public A() { InstanceCount++; Console.WriteLine("Instance constructor.Count={0}", InstanceCount); } } class Program { static void Main(string[] args) { A obA = new A();//StaticCount=1,InstanceCount=1 A obB = new A();//StaticCount=1,InstanceCount=2 A obC = new A();//StaticCount=1,InstanceCount=3 } }
A type can have only one static constructor.
It must be parameterless and it does not accept any access modifier.
static field initializers run prior to a static constructor in the declaration order.
In the absence of a static constructor, field initializers execute just before the type is used.
static constructors can be useful to write log entries.