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.

posted @ Saturday, March 17, 2007 5:48 PM

Print

Comments on this entry:

# re: Constructors in C# 3.0

Left by Richard at 3/17/2007 7:08 PM
Gravatar
I guess the second employee assignment is so the creation of the Employee seems atomic. If the assignment of FirstName threw an exception (for example), you'd never have a reference to the "incomplete" object.

# re: Constructors in C# 3.0

Left by The Igloo Coder at 3/18/2007 6:22 PM
Gravatar
Richard, the thing that I see in regards to your comment is that if an exception is raised during the assignment of: employee2.FirstName = "Joe"; there never will be an "incomplete" object. If the exception is thrown the code will be thrown up to the next highest try/catch block where the object being initialized will be out of scope even if it is not in an "incomplete" state. I'm going to have to work at trying to make this happen, and I'll post the results of my attempts.

# Constructors in C# 3.0 followup

Left by Coding in an Igloo at 3/18/2007 8:47 PM
Gravatar
In&nbsp;my previous post on Constructors in C# 3.0 I stated that I didn't understand the reasoning behind...

Your comment:



 (will not be displayed)


 
 
 
Please add 1 and 3 and type the answer here:
 

Live Comment Preview: