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:
- 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.
- The cut down on the amount of ceremony needed to implement interfaces like IRegistrations
No comments:
Post a Comment