Automatic Properties In C# 3

Published Wednesday, July 09, 2008

I came across a cool new language feature in C# 3.0 called Automatic Properties. A C# property looks like a member variable but behind the scenes are 2 related methods: a getter and a setter. The idea is that when you retrieve the value of a property, the getter is called and when you set the value of a property, the corresponding setter is called.  Properties are used all over the place and are frequently used when implementing server-side ASP.NET controls where setting a value such as the text field of a text box control causes the UI to be updated.

Declaring a property in C# looks like

string myPropertyValue;
string MyProperty
{
                get { return myPropertyValue; }
                set { myPropertyValue = value; }
}

Most properties do not have side effects and as you can imagine, declaring a lot of properties can quickly become tedious.  To alleviate this pain, C# 3 has a new construct called Automatic Properties.  In C# 3, the declaration of MyProperty becomes

string MyProperty { get; set; }

... a bit more concise and very similar to the syntax used to declare a property in a C# interface. If you wish to implement a more involved getter or setter in the future you are free to do so, without affecting the users of the class.

by Kevin

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)