Pages

Wednesday, December 21, 2011

Property shortcuts in C# 3.0

I gave a talk about the new features in C# 3.0 at the Victoria .NET Dev SIG back in December. It was a packed house, with over 100 people and the turn out surprised me considering the fact that it was less than 10 days to Christmas.

Anyway, I had promised I would post my examples to the attendees and one of them asked about it recently. So, I decided to get my act together and blog about it.

Changes to C# 3.0 include features that range from what people refer to as syntactic sugar to some really cool stuff that you can do with LINQ. And covering them all in one post will get too big (for me). So, I’ll do one feature at a time, starting with Property Shortcuts.

Property shortcuts

Typically in C# 2.0, you would implement a property as shown below -

private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value;}
}

It is a good thing to encapsulate your private data members, but more times than not, you will find yourself creating a wrapper for your private data members and nothing more. So, why not just expose these data members as public? Because, that would be bad practice – we would then lose the flexibility to change the implementation later.

C# 3.0 provides us with a compromise. You can now declare your property as shown below –

public string FirstName { get; set; }

By declaring it this way, there is no need to explicitly create a private data member to hold FirstName. So, you may ask – what is the difference between this and declaring the data member FirstName as public? The difference is that under the covers, C# creates a private data member for you. And if you decide to change the implementation later, you can.

If you think that the declaration of FirstName is very similar to how you would declare it in an interface, you would be right. Declaration of FirstName in an interface will still look like this -

interface IName
{
string FirstName { get; set; }
}

And if you wanted to declare this in an abstract class, then you can still do it -

abstract class AbstractName : IName
{
public abstract string FirstName
{ get; set; }
}

Using the abstract keyword prevents the compiler from generating private data member for the property.

Is the old syntax supported? Absolutely. The only thing that will not work is a syntax that goes something like this -

// Will not work!
public string MyProperty { get; }

The reason for that is quite obvious, actually. If this syntax was indeed legal, how would you assign a value to the property? You can’t and because there is no explicit private data member, you cannot assign a value to that either. For the same reason, using a set; in isolation will also not work.

No comments: