int num = new int(); What happens when this line executes?

前端 未结 3 837
北恋
北恋 2021-01-14 04:35

Got to know a new thing today that we can create integers by using new operator as below

int num = new int();

Now I wonder if

3条回答
  •  孤独总比滥情好
    2021-01-14 05:23

    int i = new int();
    

    is equavalent to

    int i = 0;
    

    There is no difference between them. They will generate the same IL code at all.

      // Code size       4 (0x4)
      .maxstack  1
      .locals init ([0] int32 num)
      IL_0000:  nop
      IL_0001:  ldc.i4.0
      IL_0002:  stloc.0
      IL_0003:  ret
    

    From Using Constructors (C# Programming Guide)

    Constructors for struct types resemble class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default values.

    Default value of integers is 0. Check for more Default Values Table

提交回复
热议问题