Rob Garrett - Blogs

Welcome to Rob Garrett - Blogs Sign in | Join | Help
in Search
Google

Software/Technology Discussion

Software and Technology Tid-bits

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:


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. Smiley
Share this post: Email it! | bookmark it! | digg it! | reddit!
Published Saturday, February 25, 2006 3:41 PM by Rob Garrett

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Sahil Malik said:

Thats new in .NET 2.0
February 25, 2006 5:54 PM
 

Chris Hynes said:

You could also use the new ?? syntax to make the get even shorter:

return (DateTime)(ViewState["UpdateDate"] ?? DateTime.Now);
March 6, 2006 9:41 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit

Blurb


Head Shot
Rob Garrett is a British Expat living in Maryland USA. Rob is a trained software engineer and experienced in Windows .NET development.

Rob enjoys listening to Rock music, posting to blogs, driving in the country with the sunroof open, beer (not in conjunction with country driving) and spending time with his family.

This Blog

Syndication

Powered by Community Server, by Telligent Systems