0

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?

kennyzx
  • 12,845
  • 6
  • 39
  • 83
MUYA
  • 37
  • 10
  • Can you show the generated IL? Or the relevent part of it? – Yacoub Massad Nov 05 '18 at 09:22
  • Not totally sure why this question is getting down votes, as its a good question to the uninitiated, has all the relevant code, and has a good answer – TheGeneral Nov 05 '18 at 09:33
  • It is expected the VS debugger shows the original code you write, and it is just that the Just-In-Time (JIT) compiler tries to be smart to rewrite the code for you (for better performance or whatever reasons the compiler writers know) - so the generated IL can be quite different from your original. – kennyzx Nov 05 '18 at 09:37
  • @Yacoub Massad as mentioned above,it has the iL Code – MUYA Nov 05 '18 at 14:05
  • @kennyzx ohho,maybe u r correct.thx – MUYA Nov 06 '18 at 01:41

2 Answers2

4

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

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

name = "22";
r.h_h
  • 57
  • 7