Saturday, February 09, 2008

On C# and properties (continued)

Awhile ago, I posted about a problem that I started coming across when I took software engineering with C#'s properties. Even though it was a great improvement over Java's get/set methods, there are still problems to be had (you can read the article here.

Interestingly enough, the release of C# 3.0 has fixed this problem, and in a much better way than I had thought of. I discovered this while working on RITA in Visual Studio 2008, whose property snippets (prop and propg) were updated. The syntax of the language remained the same, which is great. In C# 2.0, you can declare an abstract class to have a property with the following syntax:

public int X { get; set; }

In C# 3.0, a new feature called "automatic properties" allows you to use this syntax in concrete classes, as well. The compiler automatically creates the private variable for you, but you don't see it, all access is forced through the property, which solves the problems I mentioned in the previous post. You can prepend the get and set with access modifiers as well. For example:

public int X { get; protected set; }

This is a very clean way of doing things, and I feel rather silly for not thinking of it myself. It's a pleasant surprise in C# 3.0, since only the main features ever seemed to be touted (LINQ). It's also backwards compatible, so when I compile RITA to be compatible with .NET 2.0, it works just fine.

No comments: