What is the difference between an instance in a constructor or in a field definition?

What is the difference between this:

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

and this:

public class Foo {
    private Bar bar = new Bar();
    public Foo() { }
}
+3
source share
5 answers

The difference is that in the second case, the initialization of the field occurs before this / base constructor, and in the first case, the initialization occurs inside the constructor.

+9
source

The CLR does not support initializing fields like this. To make it work, the C # compiler overwrites your constructor. IL is as follows:

  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

, Bar Foo. , Foo. , , .

, , . , .

+6

, .

+1

, . , IL- .

0

To add an answer to Darin Dimitrov, initializing fields in a line is a good idea if you have several constructor overloads and for some reason you do not want to call other overloaded constructors.

0
source

Source: https://habr.com/ru/post/1757537/


All Articles