Another syntax twist that comes handy is the Object Initializers feature of Visual Studio 2008. What the new feature basically does is allow for a more concise initialization of class fields and properties. If we were to create several instances of the Employee class (introduced in my previous post about automatic properties), that would require several lines of code that would only perform object initialization. There is nothing wrong with this, except that the code would be verbose:

We may argue that constructors can be used for a more compact object initialization. However there are instances when we need to initialize fields or properties. The code above can be rewritten as follows:

Note that after new Employee, there are no parentheses, but a named declaration enclosed between curly braces. The syntax is flexible in that that it allows reordering of initialized fields, as well as partial initializations. In the example below I instantiated the Employee class twice, and each instance was partially initialized with a different property:

Let’s suppose that our Employee class is modified such as to have a parameterized constructor (the name and type of the parameter is not important right now, but let’s just assume we have a Boolean one). The code that initializes a class with a parameterized constructor looks like this:

Some may argue that object initializers feature is not absolutely necessary and all it does is to further complicate the syntax and make programs less readable. My personal opinion is that once this and other similar features start to appeal to the public, they will be embraced and eventually adopted by everyone. I may be on the err side, but I bet that exact thing happened when the += operator was introduced in the C language.

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5 out of 5)
Loading ... Loading …

Leave a Reply