#254 – Implementing a Read-Only Property with a Private Set Accessor
February 26, 2011 Leave a comment
One way to implement a read-only property is to provide only a get accessor, letting the code internal to the class write the property’s value by writing directly to a private backing variable.
private string personalHowl; public string PersonalHowl { get { return personalHowl; } }
However, it still might be helpful for code in the class to have a set accessor, which serves as a single place to execute whatever code is required when writing the property’s value.
You can use the private access modifier to make the set accessor available only to code within the class. The property will appear to be read-only from code outside of the class.
private string personalHowl; public string PersonalHowl { get { return personalHowl; } private set { personalHowl = value.ToUpper(); } }