Access modifiers on property get/set

To some I may be stating the obvious, but today I was happy to find out that C# lets you set a different access level on the get and set for a property. The example below will help to illustrate what I’m talking about:

public DateTime UpdateDate
{
get
{
object data = ViewState[“UpdateDate”];
return (null == data ? DateTime.Now : (DateTime)data);
}
private set
{
ViewState[“UpdateDate”] = value;
}
}

Why on Earth would you want to do this? Well, I found a perfect situation where I needed the above code. I wanted to expose a property that is essentially read only to any callers that use it, but writable to the encapsulating class. In the above case, I do not use a private field to store the property value, but the ViewState instead (property is part of a server control class), the private set allows the class to write a value to the ViewState for the property.  Now, I could have written to the ViewState directly from my class and done away with the property set altogether, but this would have resulted in many statements throughout my class code.  This way, if I want to change the logic in how my property value is persisted I can make the necessary changes in one spot.  The alternative is to use a private set function, but a private property set is so much nicer. 🙂

2 thoughts on “Access modifiers on property get/set

  1. Chris Hynes

    You could also use the new ?? syntax to make the get even shorter:
    <br>
    <br>return (DateTime)(ViewState[&quot;UpdateDate&quot;] ?? DateTime.Now);

Comments are closed.