Visual Studio 2008 – "Ah" #1 – Automatic Properties and Object Initializers

I downloaded VS08 on Monday but didn’t really get round to doing anything until today. So far so good, looks nice. Installation was a bit long, but completed without any problems.

I just tried creating a class with some properties. Nothing really interesting, except that I’m used to using the “prop” snippet.

Well guess what Visual Studio generated when I did my usual prop + tab + tab?

public string User { get; set; }

I immediately screamed BUG, but I then came across this article by Daniel Moth. And then I remembered what this was. It’s a new feature called “Automatic Properties”. This reminds me that know I can actually start using all those features that all those slides at Tech-Ed this and last year were talking about.

I’m not sure if I’m going to like these automatic properties. It doesn’t really speed up my typing because the old prop template was just one word more, and I wonder it that one word was the cost for the flexibility of a full property template (think validation in the setters). I mean now I actually have to insert the brackets and new lines into the property myself. Well, time will tell. I’ll just start using what VS gives me (by the way, you can change those snippets if you want to using Vísual Studio options).

Another feature I’m going to force myself to start getting used to is Object Initializers. This wil certainly clean up some of my code. 

User _u = new User(){ Name="Alex", Age=24 };

instead of 

User _u = User();
_u.Name = Alex;
_u.Age = 24;

(and it works nested aswell!)

Read Bard de Smet’s post about this here.

Advertisements

2 thoughts on “Visual Studio 2008 – "Ah" #1 – Automatic Properties and Object Initializers

  1. Thanks for linking to my blog. A few little notes:

    The replacement of the prop snippet by the automatic property syntax can be debated indeed, but it’s fairly straightforward to add a snippet yourself that still has the old syntax, something like cprop for “classic property”. See Tools, Code Snippet Manager.

    To be precise, the object initializer syntax of

    User _u = new User(){ Name=“Alex”, Age=24 };

    is translated into

    User t = new User();
    t.Name=“Alex”;
    t.Age=24;
    User _u = t;

    with a temporary variable. The reason is to make the assignment to _u have an atomic character.

    Enjoy C# 3.0,
    -Bart

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s