C# Variable Initialization Question

后端 未结 8 909
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 03:25

Is there any difference on whether I initialize an integer variable like:

int i = 0;
int i;

Does the compiler or CLR treat this as the same

8条回答
  •  Happy的楠姐
    2020-12-10 04:04

    I looked at the IL (using ildasm) and its true that only the int set to 0 is really set to 0 in the constructor.

    public class Class1
    {
        int setToZero = 0;
        int notSet;
    }
    

    Generates:

    .method public hidebysig specialname rtspecialname 
            instance void  .ctor() cil managed
    {
      // Code size       15 (0xf)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  ldc.i4.0
      IL_0002:  stfld      int32 ClassLibrary1.Class1::setToZero
      IL_0007:  ldarg.0
      IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
      IL_000d:  nop
      IL_000e:  ret
    } // end of method Class1::.ctor
    

提交回复
热议问题