Primary Constructors in C# 6.0

In my previous post, inspired by the Future of C# talk at GOTO, I looked at Initializers, making it possible to assign a value to an auto-property at declaration, just as with a field. This post is about another piece of syntactic sugar in the up-coming version 6.0 of C#: Primary Constructors.

Continuing the example from before, assigning values to the Movie class through a constructor, could look like this:

A constructor assigns values to the two auto properties Title and Genres.

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

Once again the constructor is missing and no need to specify a private setter. Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Movie class with two parameters: title and genres. We use our knowledge of the previous blog post, to assign the constructor parameters to properties through initializers. Magic.

The decompiled code looks as expected:

A constructor is generated with the same parameters as specified on the primary constructor and values assigned each auto-property. As with initializers, all of the syntactic sugar only exists on compile time, making it possible to execute this bad boy on previous versions of .NET.

Let’s look at a more complex example before we move on. Only one primary constructor per class is allowed. You do have the possibility to specify additional constructors through the usual syntax and you can even use this to invoke your primary constructor as illustrated in the following example:

You probably get it by now but to be explicit and consistent, let’s look at the decompiled code:

In the following post I will check out Declaration Expressions and Static Using.