Read-only properties

suggest change

Declaration

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:

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


Properties:
* Read-only properties

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
85 Properties
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script