C# 6 Preview: Autoproperty enhancements

C# 6 extends the power of autoproperties.

Up to now, if you wanted to have a read-only property, then you had two options. You could either give up on autoproperties altogether, and use a readonly backing field exposed by a property:

        private readonly string name = "Snoop";

        public string Name
                return name;

Or you could use an autoproperty with a private setter, which isn’t really read-only (it could be modified somewhere in the same class), and also means you’ll have to set the value in a constructor:

        public string Name { get; private set; }

        public Dogg()
            this.Name = "Snoop";

Fear not! C# 6 supports autoproperty initializers…

        public string Location { get; set; } = "NYC";

…which, quite conveniently, also work for getter-only properties:

        public string Name { get; } = "Snoop";

So it is now possible to declare an autoproperty without a setter, and its backing field will be implicitly declared as readonly.

These autoproperty initializers would have worked pretty nicely with a feature called primary constructors. But since this feature has been dropped, the usefulness of getter-only autoproperty initializers is restricted to readonly properties.

It is also worth mentioning this note about mutability from the C# feature descriptions [PDF]:

“This is about expressing types more concisely, but note that it also removes an important difference in the language between mutable and immutable types: auto-properties were a shorthand available only if you were willing to make your class mutable, and so the temptation to default to that was great. Now, with getter-only auto-properties, the playing field has been leveled between mutable and immutable.”

Eventually you’ll also be able to initialize getter-only autoproperties from within constructors, but at the time of writing this article, it is not yet supported in the latest CTP (Visual Studio 14 CTP4).

Leave a Reply

Your email address will not be published. Required fields are marked *