Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a static constructor called in C#?

Tags:

c#

static

People also ask

Can a static method call a constructor?

Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.

When and how often is a static constructor called MCQ?

9. When and how many times a static constructor is called? Explanation: Those are called at very first call of object creation. That is called only one time because the value of static members must be retained and continued from the time it gets created.

How many times does the constructor get called for a static class?

A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.


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
    }
}