Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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;
like image 287
JadeMason Avatar asked Jun 26 '09 19:06

JadeMason


1 Answers

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.

like image 146
mqp Avatar answered Sep 21 '22 07:09

mqp