Read-only properties

suggest change


A common misunderstanding, especially beginners, have is read-only property is the one marked with readonly keyword. That’s not correct and in fact following is a compile time error:

public readonly string SomeProp { get; set; }

A property is read-only when it only has a getter.

public string SomeProp { get; }

Using read-only properties to create immutable classes

public Address
    public string ZipCode { get; }
    public string City { get; }
    public string StreetAddress { get; }

    public Address(
        string zipCode,
        string city,
        string streetAddress)
        if (zipCode == null)
            throw new ArgumentNullException(nameof(zipCode));
        if (city == null)
            throw new ArgumentNullException(nameof(city));
        if (streetAddress == null)
            throw new ArgumentNullException(nameof(streetAddress));

        ZipCode = zipCode;
        City = city;
        StreetAddress = streetAddress;

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents