Wednesday, June 25, 2008

Defining .NET properties the easy way

Once you've done a fair amount of programing in .NET, it quickly becomes tiresome to define your custom properties in code:

private int myProperty;
public int MyProperty

{
get { return myProperty; }
set { myProperty = value; }
}

It gets to the point where you seriously consider just declaring everything as a field instead:

public int MyProperty;

But resist the temptation! There are downsides to this including difficulties with databinding and all sorts of issues if you later change your mind and want them to be properties.

So, stick with properties but make your life a little easier by using the built-in prop snippet. When you want to create a new property, just type prop and hit Tab twice and Visual Studio will insert a nice template for creating the property. You can tab through the fields in the template and easily change the type and name to what you want.

And here's the really good news: the new version of C# that comes with Visual Studio 2008 includes a feature called Automatic Properties. This allows you to define basic properties using this syntax:

public int MyProperty { get; set; }

Behind the scenes, the C# compiler translates this to (basically) the same code as if you'd used the more traditional syntax.

For more information on Automatic Properties, see this post from Bart De Smet's blog.

0 comments: