Auto-properties with initializers (C# 6)

Submitted by Robert MacLean on Mon, 03/30/2015 - 15:59
C# 6
Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

A big design trend in C# 6 is the removal of ceremony from code. Ceremony is the amount of code you need to write, to write the code that actually matters. It is the fluff that is there because it is needed by C# and not to solve your problem. Auto-properties are a great example of removal of ceremony & in C# 6 they have been improved further.

In C# 1 we would would type out the full property with the getter & setter and a field. One nice feature is you could initialise the value the field, thus giving the property a default value. For example, like this:

private int csharpOne = 42;

public int CSharpOne
    get { return csharpOne; }
    set { csharpOne = value; }

In C# 2 we got the (syntactic sugar) feature for one line properties. The compiler though would generate the field, the getter and the setter automatically in the compiled code. However, the loss of the field, meant the only way to assign a default value was in the constructor, as in the following example:

public int CSharpTwo { get; set; }

public AutoProperties()
    CSharpTwo = 42;

On one hand, the single line property is great and is an example of less ceremony adding readability, but when we need to assign a default value we add more ceremony and ultimately increase complexity and the potential for errors because there is no obvious way to see the constructor is assigning a value unless you go and check it.

C# 6 simplifies solves this with a new syntax to assign a default value:

public int CSharpSix { get; set; } = 42;

That is pretty awesome!