Posted on 8/24/2009 9:37:14 PM by Justin Etheredge
I know that this post is going to be old hat for the vast majority of you, and if this is the case, then please just ignore this post. More than likely though, you’ve come across someone that needs to read this post, and if so please pass it on!
If you’ve been using C# 3.0 for long enough then you have probably started using a neat little piece of syntactic sugar called automatic properties.
For the uninitiated, instead of writing this:
public class Person
{
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
You get to write this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
And yes, we aren’t performing magic, it is just shorthand for the properties above, and you can clearly see that if you reflect it. I won’t show you the IL here, but you can just trust me. :-)
Unfortunately, for most developers, the above use of automatic properties is where the fun stops. Once they get to the point where they need to have a read-only property, they fall back to their old tricks and write this:
public class Person
{
private string firstName;
public string FirstName
{
get { return firstName; }
}
private string lastName;
public string LastName
{
get { return lastName; }
}
}
Boooooooo! You don’t need to do that silly developer. You just need to do this:
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
}
See, now how hard was that? Now you have a public property with a private setter. You can also use protected or internal, so that you can set it from inherited classes and within the same assembly:
public class Person
{
public string FirstName { get; protected set; }
public string LastName { get; internal set; }
}
And yep, you can even create a write-only property, although this has less usefulness:
public class Person
{
public string FirstName { private get; set; }
public string LastName { private get; set; }
}
So you have all of the functionality you need, unless you require some custom logic be inside of your getters or setters. If you haven’t been aware of these features of automatic properties then first get out from under your rock, and second, go out there and delete some code! Hope you enjoyed!