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

。_饼干妹妹 提交于 2019-12-01 08:08:26
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

The answer is in section 4.1.2 of the C# language spec:

All value types implicitly declare a public parameterless instance constructor called the default constructor. The default constructor returns a zero-initialized instance known as the default value for the value type:

Like any other instance constructor, the default constructor of a value type is invoked using the new operator. For efficiency reasons, this requirement is not intended to actually have the implementation generate a constructor call. In the example below, variables i and j are both initialized to zero.

class A
{
    void F() {
        int i = 0;
        int j = new int();
    }
}

In terms of doing things without using a default constructor, such as

int x = 1;

That's covered by section 4.1.4 of the C# Language Spec:

Most simple types permit values to be created by writing literals (§2.4.4). For example, 123 is a literal of type int

I think, you are looking for

int num = default(int);

This is also useful when facing compilation error, Unassigned local variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!