Friday, September 26, 2014

A First Look at Using C# 6 - Auto Properties

This is the second post about the C# 6 features I used when moving Nancy.Linker over to C# 6. The first part was about primary constructors. This one in about the new auto-property features.

Auto-Property Initializers and Getter-Only Auto-Properties

Just like fields can be initialized from primary constructor arguments in C# 6 so can auto properties. In Nancy.Linker this is used in the Registration class where cuts out a good deal of ceremony.

Furthermore auto properties do not need to a setter anymore. This is very different from autoproperties with a private setter, because an auto-property without a setter is immutable, where as an auto-property with a private setter only protected against code outside of the class mutating it.

The Registration class in Nancy.Linker implements the IRegistrations interace from Nancy, which looks like this:

Notice that this is 3 getter-only properties. Until now you would have implement these either with explicit getters, or as auto-properties with setters. In C# 6 their implementation can follow the interface more closely and as an added bonus the whole class becomes immutable. The code for the Registration class becomes:

I like these 2 features because:
  1. They make creating immutable types in C# a lot easier, which I think we will see a whole lot more of in C# code in the near future.
  2. The cut down on the amount of ceremony needed to implement interfaces like IRegistrations