What is the difference between instantiation in constructor or in field definition?

后端 未结 5 1694
后悔当初
后悔当初 2021-01-14 16:23

What is the difference between this:

public class Foo {
    private Bar bar;
    public Foo() { bar = new Bar(); }
}

and this:



        
5条回答
  •  礼貌的吻别
    2021-01-14 16:42

    The CLR does not support initializing fields like this. To make it work, the C# compiler rewrites your constructor. The IL looks like this:

      IL_0000:  ldarg.0
      IL_0001:  newobj     instance void ConsoleApplication1.Bar::.ctor()
      IL_0006:  stfld      class ConsoleApplication1.Bar ConsoleApplication1.Foo::bar
      IL_000b:  ldarg.0
      IL_000c:  call       instance void [mscorlib]System.Object::.ctor()
      IL_0011:  ret
    

    Note that the Bar constructor is called before the Foo base constructor. Which is the difference with your other snippet, there the Foo base constructor is called afterward. This will rarely make a difference, unless the field is inherited and the base class constructor does something with it.

    Or if field initializers depend on each other, they are initialized in strict textual order. You can control the order by doing it explicitly in the constructor.

提交回复
热议问题