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

前端 未结 3 721
北恋
北恋 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:26

    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

提交回复
热议问题