Desugaring object initializers

2013-10-17

Do you sometimes shiver when you see yourself writing line after line of assignments when initializing a new object? Maybe something like this:


Foo foo = new Foo();
foo.A = 1;
foo.B = 2;
foo.C = 3;
foo.D = 4;
foo.E = 5;

As you can see, this syntax is quite verbose. Fortunately, C# added some syntactic sugar to make your life easier.

Meet the object initializer

Starting with C# 3 some syntactic sugar was added to help you with initializing objects. Using this new syntax the previous code can be changed to:


Foo foo = new Foo
{
    A = 1,
    B = 2,
    C = 3,
    D = 4,
    E = 5
};

This syntax is called an object initializer. If you desugare this code you will see the following:


Foo __foo = new Foo();
__foo.A = 1;
__foo.B = 2;
__foo.C = 3;
__foo.D = 4;
__foo.E = 5;
Foo foo = __foo;

A local temporary variable is created by the compiler. In the generated IL code, this variable uses the special naming construct with angle brackets so you don’t get conflicts with your own code. Then the properties are assigned and the temporary variable is assigned to the actual variable.

On a side note, do you think the following the code compiles?


Foo foo = new Foo
{
    A = 1,
    B = 2,
};

As you can see, you have a comma following the assignment of B. And yes, this code will compile! Why? The compiler allows the extra comma in object initializers to make code generation easier. You don’t have to check if you are generating code for the last property you want to set, you can jus add the comma.

Anonymous types

While object initializers are a nice form of syntactic sugar in these types of scenarios, they are actually required when working with anonymous types. An anonymous type is a type that is defined by the way it’s initialized:

var myAnonymousType = new { X = 42 };

By using the object initialization syntax, you define a new property called X for your anonymous type. After this line, your object will have a property X. You can’t just add a new property to it by doing something like myAnonymousType.Y = “This won’t work”.

Why? Well, anonymous types are also a form of syntactic sugar. In a future blog post we will look at anonymous types in more detail but in essence, the compiler generates a class for you with an angle bracket name and the properties that you use in the object initializer.

So, that’s the idea behind object initializers. It’s just a nice way of quickly initializing a new object or creating a new anonymous type.

Feedback? Questions? Please leave a comment!