Struct initialization and new operator

后端 未结 4 1351
無奈伤痛
無奈伤痛 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:07

    This is covered in the C# specification section 5.3 dealing with "Definite Assignment":

    a struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.

    and:

    An initially unassigned variable (Section 5.3.2) is considered definitely assigned at a given location if all possible execution paths leading to that location contain at least one of the following:
    * A simple assignment (Section 7.13.1) in which the variable is the left operand.
    * ...

    As such, this also works:

    void Main()
    {
        X x;
        x.a = 1;
        x.b = 2;
    
        x.Dump();
    }
    
    public struct X
    {
        public int a;
        public int b;
    }
    

    You can test this in LINQPad.

    Note that there is no way for the compiler to prove that the struct-type variable is considered definitely assigned if you call code on it, and that's what you're doing with a property. As such, before you can use a property on the struct-type variable, it has to be definitely assigned.

提交回复
热议问题