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 using auto-properties as it eliminates a lot of boilerplate code and encourages use of the property member rather than the backing field. However, when using an auto-property I lose the "readonly-ness" of my backing field. I understand the compiler/runtime is able to take advantage of some performance enhancements when a field is marked this way, so I would like to be able to mark my auto-property as readonly, something like this:
[ReadOnly]
public string LastName { get; }
rather than
private readonly string _LastName;
public string LastName
{
get
{
return _LastName;
}
}
Is there some mechanism already available to do this? If not, is the performance gain from the custom backing field being readonly really worthwhile?
Exposing the field as public is another option, I suppose, it just seems wrong to expose a field that way. i.e.
public readonly string LastName;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…