Search code examples
c#visual-studioconstructorobject-initializersintermediate-language

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


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?


Solution

  • 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.