Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need static constructors?

First of all, I got an answer in What is the use of static constructors?, but I want an answer in this context.

Here is my C# static class:

public static class BasicClass
{
    static int i = 0;
    static BasicClass()
    {
        i = 10;
    }

    public static void Temp()
    {
        //some code
    }


    public static void Temp1()
    {
        //some code
    }
}

Inside this I have a static variable i which is initialized to 10 when it is first called. So basically it may be the purpose of a static constructor but the same thing can be achieved without declaring a static constructor by initializing the static int i = 10 which serves the same purpose that is gets initialized only once.

Then why do we need a static constructor? Or am I completely wrong in understanding the concept or use of static constructors?

like image 287
iJade Avatar asked Mar 06 '13 14:03

iJade


2 Answers

Well, in your example it is not indeed needed, but and imagine when i value has to be read from a database, text file, or any other resource? You might need something like:

static BasicClass()
{
    using (SomeConnection con = Provider.OpenConnection())
    {
        try
        {
            // Some code here
        }
        catch
        {
            // Handling expeptions, setting default value
            i = 10;
        }
    }
}

Now it is not possible to declare and initialize your static field, you're better served using a static constructor

like image 38
RMalke Avatar answered Oct 11 '22 19:10

RMalke


If you compile that class into an assembly, then use ILSpy or similar to disassemble the result, you will notice that all static member initialization is performed in the static constructor.

For instance, the following C# code:

public static class BasicClass
{
    static int i = 10;
}

Will produce IL equivalent to:

public static class BasicClass
{
    static int i;

    static BasicClass()
    {
        i = 10;
    }
}

In other words, direct initialization is only syntactic sugar provided by the C# compiler. Under the hood, a static constructor is still implemented.

like image 126
Frédéric Hamidi Avatar answered Oct 11 '22 19:10

Frédéric Hamidi