Is it possible to force an auto-property to use a readonly backing field?

后端 未结 6 874
不思量自难忘°
不思量自难忘° 2020-11-30 14:02

My project contains a large number of classes with properties whose backing field is marked readonly as they are only set at construction. As a matter of style, I like usin

6条回答
  •  星月不相逢
    2020-11-30 14:13

    No it is not and if it was the feature would be useless without significant tweaking.

    A readonly field can only be verifiably set from a constructor. A auto-implemented property can only be set from the generated setter. These are incompatible requirements and will produce unverifiable code.

    Yes you could potentially make the compiler smart enough to ignore the setter and go straight to the backing field in the constructor. But in the setter itself would still be unverifiable. The compiler would need to omit it from the generated code as will producing a truly read-only property. This produces another contradiction because you would still need to do an assignment statement against the property.

    Foo() {
      SomeProperty = "somevalue";
    }
    

    In this case the code looks like it's calling a setter on a property. But there is actually no setter to be called since it must be omitted from the final code.

    EDIT

    This is not saying it can't be done. It can but it would require a bit of work from C#.

    In particular they would have to provide a way to set the backing field of a property which cannot have a setter. There are several ways this could be done.

    • Give users access to the backing field of an auto-implemented property
    • Allow the setter style syntax even though there is no setter and let the compiler translate it to a field access under the hood
    • Invent some new syntax

    I'm not saying any of these are good options, just possibilities to make this type of feature work .

提交回复
热议问题