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;
I'm afraid not, but you can do this:
public string LastName { get; private set; }
Not quite as good as readonly
, but not too bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With