Thomas Ardal

Freelance software consultant and entrepreneur building SaaS applications like elmah.io

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:

public class Movie
{
    public string Title { get; private set; }
 
    public List<string> Genres { get; private set; }
 
    public Movie()
    {
        Title = "The Big Lebowski";
        Genres = new List<string> { "Comedy", "Crime" };
    }
}

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:

public class Movie
{
    public string Title { get; } = "The Big Lebowski";
 
    public List<string> Genres { get; } = new List<string> { "Comedy", "Crime" };
}

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:

public class Movie
{
    private readonly string <Title>k__BackingField
    private readonly List<string> <Genres>k__BackingField;
    
    public string Title
    {
        get { return this.<Title>k__BackingField; }
    }
 
    public List<string> Genres
    {
        get { return this.<Genres>k__BackingField; }
    }
    
    public Movie()
    {
        this.<Title>k__BackingField = "The Big Lebowski";
        this.<Genres>k__BackingField = new List<string>
        {
            "Comedy",
            "Crime"
        };
        base..ctor();
    }
}

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.

Show Comments