When is a static constructor called in C#?
When the class is accessed for the first time.
Static Constructors (C# Programming Guide)
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
It's not quite as simple as you might expect despite straightforward documentation. Jon Skeet's article http://csharpindepth.com/Articles/General/Beforefieldinit.aspx goes into this question in details.
Summary:
Static constructor is guaranteed to be executed immediately before the first reference to a member of that class - either creation of instance or own static method/property of class.
Note that static initilaizers (if there is no static constructor) guaranteed to be executed any time before first reference to particular field.
The static constructor is called before you use anything in the class, but exactly when that happens is up to the implementation.
It's guaranteed to be called before the first static member is accessed and before the first instance is created. If the class is never used, the static constructor is not guaranteed to be called at all.
In case static method is called from parent class, static constructor will not be called, althogh it is explicitly specified. Here is an example b constructor is not called if b.methoda() is called.
static void Main(string[] args)
{
b.methoda();
}
class a
{
public static void methoda()
{
//using initialized method data
}
}
class b : a
{
static b()
{
//some initialization
}
}