Struct initialization and new operator

后端 未结 4 1359
無奈伤痛
無奈伤痛 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 reason one is valid while the other is not is that you cannot call methods on uninitialised objects. Property setters are methods too.

    public struct X
    {
        public int a;
        public void setA(int value)
        { this.a = value; }
    }
    
    public struct Y
    {
        public int a { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            X x;
            x.setA(1); // A: error
            x.a = 2; // B: okay
    
            Y y;
            y.a = 3; // C: equivalent to A
        }
    }
    

    The reason that is not allowed is that the property setter could observe the uninitialised state of the object. The caller does not know whether the property setter merely sets a field, or does more than that.

提交回复
热议问题