Read-only auto-properties (C# 6)

C# 6

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

Continuing from the previous post on auto-property initializers, 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’s look at C# 1 and how we handled this in the past. In C# 1, we could remove the setter of a property to create a read-only property:

private int csharpOne = 42;

public int CSharpOne
{
    get { return csharpOne; }
}

With C# 2 auto-properties, we didn’t receive support for a read-only version. The closest we could get was limiting 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, allowing us to assign the value using either the new auto-property initializer syntax or in the constructor. For example:

public int CSharpSix { get; } = 42;

The changes to auto-properties will bring many benefits for cleaner code. What do you think?