#253 – Implementing a Read-Only Automatic Property
February 25, 2011 1 Comment
When using the automatic property syntax,C# requires that you define both a get and a set accessor. But with the default syntax, you end up with a read/write property.
public int Age { get; set; }
But what if we want a read-only property, from the client code’s perspective? Since we’re required to define the set accessor, it looks like client code would always be able to write to the property.
The solution is that we can add a private access modifier to the set accessor.
public int Age { get; private set; }
With the set accessor private, code external to the class can read the property’s value, but not write to it. But code within the class can still write to the property.
In Visual Studio, the “propg” code snippet is your friend for this.