C#, immutability and public readonly fields

C# 6.0 now supports auto-property initializers.

The auto-property initializer allows assignment of properties directly within their declaration. For read-only properties, it takes care of all the ceremony required to ensure the property is immutable.

You can initialize read-only properties in constructor or using auto-initializer

public class Customer
{
    public Customer3(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public string FirstName { get; }
    public string LastName { get; }
    public string Company { get; } = "Microsoft";
}

var customer = new Customer("Bill", "Gates");

You can read more about auto-property initializers here


It is an obvious omission from properties that you cannot write something like:

public T2 Item2 { get; readonly set; } 

I'm not even sure readonly is the best word to use to mean "can only be set in the constructor", but that's what we're stuck with.

This is actually a feature that many people have requested, so let's hope that it will be introduced in a hypothetical new version of C# some time soon.

See this related question.


You may not need to add any logic to a setter in the future, but you may need to add logic to a getter.

That's a good-enough reason enough for me to use properties rather than exposing fields.

If I'm feeling rigorous then I'd go for full immutability (explicit readonly backing fields with exposed getters and no setters). If I'm feeling lazy then I'd probably go for "agreed immutability" (auto-properties with exposed getters and private setters).