Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are static fields initialized in C#? [duplicate]

Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

new A()
_A == null
static A()
new A()
_A == A

The code:

public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}
like image 830
Prankster Avatar asked Nov 21 '22 11:11

Prankster


1 Answers

This is correct.

Your static initializers, then the static constructor is run before your standard constructor, but when it runs, it's using new A(), so passing through your non-static constructor path. This causes the messages you see.

Here is the full path of execution:

When you first call var a = new A(); in your program, this is the first time A is accessed.

This will fire off the static initialization of A._A

At this point, A._A constructs with _A = (new A()).I();

This hits


Console.WriteLine("new A()");
if (_A == null)
    Console.WriteLine("_A == null");        

since at this point, _A hasn't been set with the returned, constructed type (yet).

Next, the static constructor A { static A(); } is run. This prints the "static A()" message.

Finally, your original statement (var a = new A();) is executed, but at this point, the statics are constructed, so you get the final print.

like image 123
Reed Copsey Avatar answered Jan 09 '23 22:01

Reed Copsey