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

后端 未结 6 882
不思量自难忘°
不思量自难忘° 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:20

    As of C# 6.0 the answer is yes. Your example can be written as below, and the compiler automatically generates a read-only field behind the property. This is called a getter-only auto-property.

    public string LastName { get; }
    

    From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

    Getter-only auto-properties are available in both structs and class declarations, but they’re especially important to structs because of the best practice guideline that structs be immutable. Rather than the six or so lines needed to declare a read-only property and initialize it prior to C# 6.0, now a single-line declaration and the assignment from within the constructor are all that’s needed. Thus, declaration of immutable structs is now not only the correct programming pattern for structs, but also the simpler pattern—a much appreciated change from prior syntax where coding correctly required more effort.

提交回复
热议问题