Struct initialization and new operator

后端 未结 4 1352
無奈伤痛
無奈伤痛 2021-02-12 12:58

I have two similar structs in C#, each one holds an integer, but the latter has get/set accessors implemented.

Why do I have to initialize the Y struct with

4条回答
  •  日久生厌
    2021-02-12 13:19

    The new operator for value types runs the specified constructor. Unlike with reference types, this is optional, so if you don't use new, the default constructor is implicitly run (you cannot specify your own default constructor, so it always has the effect of giving the default value to the fields for their types).

    As for why the compiler error, I'm not really sure. Interestingly, in the C# Interactive window,

    public struct Y
    {
        public int a { get; set; }
    }
    Y test;
    test.a = 5;
    

    works just fine.

提交回复
热议问题