Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static fields initialization occurs before the static constructor?

Tags:

c#

.net

static

The following code:

static void Main(string[] args)
{
    Console.WriteLine("0");
    string h = Foo.X;
    Console.WriteLine("2");
}

public static class Foo
{
    public static string X = ((Func<string, string>)delegate(string g)
    {
        Console.WriteLine(g);
        return (g);
    })("_aaa");

    static Foo()
    {
        Console.WriteLine("ctor");
    }
}

Will print:

0
_aaa
ctor
2

I know about the beforefieldinit behavior (with/without static constructor etc.).

The thing which I don't understand is why the ctor (in the output) is after _aaa?

It doesn't make any sense, what if I want to initialize variables in the constructor?

Question

Why does the initialization of X is before the ctor?

like image 930
Royi Namir Avatar asked Nov 27 '11 11:11

Royi Namir


People also ask

Are static variables initialized before constructor?

All static members are always initialized before any class constructor is being called.

Is a static field initialized in the constructor?

You can define a static field using the static keyword. If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Are static variables initialized first?

It is a variable which belongs to the class and not to object(instance ). Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.

Why do we need to initialize static variables?

A static object of class type will use the default constructor if you do not initialize it. Automatic and register variables that are not initialized will have undefined values.


1 Answers

The reason ctor is after the field initializers is because that's the way it is specified. From the C# specification (emphasis is mine):

10.5.5.1 Static field initialization The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class

If you want to have total control of your initialization order, move it all inside the constructor.

like image 62
João Angelo Avatar answered Oct 21 '22 09:10

João Angelo