Struct initialization and new operator

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

    In first case you just assigning field. It doesn't involve actual using of structure, just setting value into memory (struct address + field offset on stack).

    In second case you calling method set_a(int value), but fail because variable is uninitialized.

    In third case constructor initializes it for you, so using variable is ok.

    Update: Here comes the specification!

    "12.3 Definite assignment" (page 122 of ecma-334).

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

提交回复
热议问题