Auto-properties with Initializers in C# 6.0

In the previous post (inspired by the Future of C# talk at GOTO), I showed you how to enable the C# 6.0 Language Preview in Visual Studio 14 CTP 3. In this post, I’ll introduce you to the first of the new features in C# 6.0: Auto-Properties with Initializers.

So what does Auto-Properties with Initializers try to improve? Let’s look at a simple example where I want to create a new object containing a couple of auto-properties with default values:

A constructor assigns default values to the two auto properties Title and Genres. In the real world, the actual values would probably be parameters to the constructor, but I’ll save that scenario for a later post.

Let’s look at how initializer in C# 6.0 can be used to optimize the code above:

Notice that the constructor is missing. The value of the properties is assigned directly on each property. Another detail worth mentioning is, that auto-properties no longer require both a getter and a setter.

The highlighted advantage of this in other posts and articles seems to be the saved number of lines, but I think that there’s a more obvious advantage writing default values this way (besides supporting primary constructors): We now have a uniform way of assigning values to properties and fields. I

So how did Microsoft implement this behind the scene? Let’s take a look at the compiled code through ILSpy:

Basically an exact copy of the code written in example 1. This being syntactic sugar, should make it possible to execute code including initializers to execute on previous versions of .NET.

In the next post I will look at Primary Constructors, which fits perfectly with initializers.