开发者

C# class instance field default value assignment plus default constructor equals double assignment?

开发者 https://www.devze.com 2023-04-04 22:13 出处:网络
I\'m new to c# and read that instance fields were initialized before a default constructor call. Does that mean that they are doubly initialized?

I'm new to c# and read that instance fields were initialized before a default constructor call. Does that mean that they are doubly initialized?

class MyClass
{
  public int value;

}

Would that mean that value gets the default 0 then the the default constructor is called and assigns 0 again开发者_运维知识库?


No, the parameterless constructor created by the compiler doesn't perform an assignment to the field unless you specify a variable initializer. So in a class like this:

class Test
{
    int a = 0;
    int b = 1;
    int c;
}

... the generated constructor looks like this in IL:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       22 (0x16)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.0
  IL_0002:  stfld      int32 Test::a
  IL_0007:  ldarg.0
  IL_0008:  ldc.i4.1
  IL_0009:  stfld      int32 Test::b
  IL_000e:  ldarg.0
  IL_000f:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0014:  nop
  IL_0015:  ret
} // end of method Test::.ctor

Note the assignments to a and b but not c. Normally the difference between explicitly assigning a value of 0 and leaving it to be the default value is not observable, but it's present in the IL. (A subclass which decided to call some virtual method before calling the base class constructor could demonstrate the difference, although I suspect that would violate the CLS.)

0

精彩评论

暂无评论...
验证码 换一张
取 消