New C# 6 Features – Auto Property Initializers

Recently, I presented thirteen planned C# 6 features to my peers in one of our lunchtime ‘Brown Bag‘ talks. The format was informal, and included a ‘panel’ of judges formed of some of the more experienced developers on the team. After each feature was demonstrated, each member of the panel held aloft their score out of 10.

Some of the feedback on the features was quite interesting, enough so to present them in a series of blog posts.

There’s plenty of information already out there, a good selection contained in the following articles.

Anyhow, let’s dive into the first feature, Auto Property Initializers.

So, up until C# 5, this is how we declare and initialise auto properties:

class AutoPropertyInitializerOld
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }

    //public string Prop3 { get; } //Error: "Auto-implemented properties must have set accessors."
    private string field3;
    public string Prop3 { get { return field3; } }

    public AutoPropertyInitializerOld()
    {
        Prop1 = 0;
        Prop2 = "Hello";
        field3 = "SomeVal";
    }
}

Note that:

  • Our declaration and assignment are in different places.
  • We can’t have a ‘get’ only auto-property

However with C#6 we can now say:

class AutoPropertyInitializerNew
{
    public int Prop1 { get; set; } = 1;
    public string Prop2 { get; set; } = "Goodbye";

    //Can have an initializer on a read-only property - now we can have auto-properties on immutable types.
    public string Prop3 { get;  } = "I can still be set";
}

So what are the benefits of this? Well, we now have some short hand for declaring properties, which is nice, but the best thing about this is something I’ve alluded to in the comments:

Currently, if we want an immutable type, we cannot have an auto-property, as an auto-property must have a get and set accessor on it. Some will argue that private set makes a type immutable:

class UsingPrivateSet
{
    //Can have an initializer on a read-only property - now we can have auto-properties on immutable types.
    public string ImmutableProp3 { get;  private set; } 
}

This is true for simple types with no internal functionality that modifies state, however, more complex types classes may mutate the state of the object from private or even public methods. Inherently, use of private set does makes a class’ immutability dependent on other implementation factors.

Now we can have a get-only auto-property:

class GetterOnlyDemo
{
    //Can have an initializer on a read-only property - now we can have auto-properties on immutable types.
    public string ImmutableProp3 { get;  } = "I can still be set";
}

And the compiler is smart enough to enforce the assignment of an auto-property, throwing an error if it is not set.

Panel score: This was presented in conjunction with Primary Constructors (next), so we’ll see the score there.

Leave a Reply