Menu

C# 6 Features: Auto Property Initializers

June 27, 2015 - .NET, C#

This is part of a series of posts covering new C# 6 features. Currently there are posts covering the following:
String Interpolation
Expression-bodied Members
Improved Overload resolution
The Null Conditional operator
Auto-Property Initializers

Object Oriented programming has, like any paradigm, found itself refined as time moved forward. The core principle is rather straightforward- you have an object, which has some state, and you can send messages to it to change it’s state.

This eventually gave rise to a pattern known as “Setter/Getter”. Take this Java example:

We see this pattern quite frequently. In order to control access to the internal state of the class, we need to write methods that act as a go-between. We could expose the fields directly- as public members- however, this would allow your classes state to change all over the place. For example, if you have a class which accepts an interface callback which get’s called during your logic, you would want to prevent your class state from changing during that operation, but without control over when the state changes (and even if) you wouldn’t be able to do this.

C# introduced a first-class concept called “Properties”. Properties are dealt with effectively like public fields, however, you can insert code to act as part of the setter or getter. The above example would look like this:

A bit more straightforward- and certainly shorter. It’s still an awful lot of boilerplate. C# later introduced “Auto” properties:

Auto properties are more or less syntax sugar. Doing it this way will implicitly create a backing field for the property and the “standard” sort of setter/getter logic we would expect. Of course it is possible to create read only, private, write-only, private write, etc. styles using auto properties as well. The one caveat has always been that you cannot initialize that backing field as part of the declaration. C# 6 has added the capability to have an initializer on an auto-property for this purpose:

For this example, of course, it doesn’t really change anything; however there are plenty of cases where you have for example class-type member properties that you wish to have default to a known value. Previously, you would have needed to set the value in the constructor, or revise your declaration to instead have a backing field that you could control directly. Now we have another tool in our toolbox of capability when it comes to writing C# code. I can think of numerous instances where this sort of capability would have lent itself to more straightforward code, so here is hoping I’ll be able to use it on professional projects sooner rather than later (We’re still using .NET 4.0 and C# 4)

Have something to say about this post? Comment!