Field initializer is in constructor in IL, but not when debugging in Visual Studio

117 views Asked by At

In IL code,the field initialization is in constructor.

Field initialization in Constructor

But in VS2017 debug ,the field initialization is not in constructor, but in class.

Field initialization in VS Debug

Source Code:

class A
{
    public int id = 0;
    public A()
    {
        id = 99;
    }
}

class B:A
{
    string name = "11";
    public B()
    {
        name = "22";
    }
}

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
    }
}

Can someone explain this to me?

2

There are 2 answers

2
CodeCaster On BEST ANSWER

That doesn't look like a problem. The compiler moves field initializations into the constructor, but the debug information tries to follow the C# code as closely as possible.

So actually your IL will look something like this:

class B:A
{
    string name;

    public B()
    {
        // hidden from debugger
        name = "11"

        // here's where the debugger is told the constructor starts
        name = "22";
    }
}

That's why your breakpoint on public B() shows that name is already initialized.

0
r.h_h On

You need to move your debugger's arrow (the yellow one, idk what's the name) until it past the

name = "22";