Skip to content

readonly struct C# 7.2correctness

Allow a struct to be declared immutable.

C# 7.2 allows a struct to be marked readonly to indicate that it is immutable. By doing so the compiler can enforce that all fields and properties of the struct are also marked read-only or init-only while allowing the struct to be passed by reference without the risk of modification.

Code

C#
readonly struct CurrencyAmount
{
    public CurrencyAmount(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public decimal Amount { get; init; }
    public string Currency { get; init; }

    public override string ToString() => $"{Amount} {Currency}";
}
C#
struct CurrencyAmount
{
    public CurrencyAmount(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    // Didn't mean to allow this to be changed
    public decimal Amount { get; set; }
    public string Currency { get; set; }

    public override string ToString() => $"{Amount} {Currency}";
}

More information