Read-only auto-properties (C# 6)

Submitted by Robert MacLean on Tue, 03/31/2015 - 07:59
C# 6
Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

Continuing on from the previous post with auto-property initialisers, the second enhancement to auto-properties in C# 6 is proper support for read-only properties.

Before we get to the C# 6 solution, let us look at C# 1 and how we have done this in the past. In C# 1 we can remove the setter of a property to have a property which is read-only:

private int csharpOne = 42;

public int CSharpOne
    get { return csharpOne; }

With C# 2 auto-properties we did not get support for a read-only version. The closest we could get to the same functionality is limit the accessibility of the setter, for example:

   public int CSharpTwo { get; private set; }

Finally with C# 6 we get true read-only support in auto-properties, which allows us to assign the value using either the new auto-property initialiser syntax or in the constructor. For example:

public int CSharpSix { get; } = 42;

The changes to auto-properties really will have a lot of benefits for cleaner code. What do you think?