uncategorized

Constructors in C# 3.0

Another of the new features in C# 3.0 (part of Visual Studio Orcas) is the ability to do initialize objects inline and without the need for special constructors.  As you can see in the image below, this is done by initializing an object with curly braces and a “Property = <value>, Property = <value>, …” syntax.  Also note that you don’t have to use all the properties in when filling in the constructor.

initializer

Here’s what you see when you look at the disassembled code when I only initialize one Employee object.  When I first looked at this I was a little bit shocked.  In the first few lines it does exactly what I expected it to do by creating the employee variable and then assigning the property values in separate lines of code.  I don’t fully understand why it is creating a second Employee variable at the end and making it equal the first one.

initializerdisassembled

One of the nice IDE features that goes with this is the autocomplete popup while you’re typing in the “Property = <value>” assignments.  You see in the first image on this post that the autocomplete popup displays only the remaining unused properties in its list.  If you try to use a property more than once in the initialization of the object you will get a compile time error.

Once C# 3.0 ships I think that this will be one of the more widely used new language features.  Developers won’t have to write and chain together numerous different constructors in their objects which reduces the maintenance overhead and increases the flexibility of the code.