Skip to content

readonly instance members C# 8.0performancecorrectness

Allow struct members that do not modify state to be annotated as such.

The readonly struct C# 7.2 feature allowed you to create structs that were immutable. However, it was an all or nothing proposition.

With C# 8.0 you can now mark individual members as readonly to indicate that they do not modify the state of the struct. This allows the compiler to make performance optimizations and also helps document the intent of the code.

Code

C#
struct Licence
{
    private readonly string[] refParts;

    public Licence(params string[] refParts)
    {
        this.refParts = refParts;
    }

    public readonly string Reference
    {
        get { return string.Join('/', refParts); }
    }

    public DateTime Expiration { get; set; }

    public override readonly string ToString()
    {
        return Reference + "//" + Expiration.Year + "/" + Expiration.Month;
    }
}
C#
struct Licence
{
    private readonly string[] refParts;

    public Licence(params string[] refParts)
    {
        this.refParts = refParts;
    }

    public string Reference
    {
        get { return string.Join('/', refParts); }
    }

    public DateTime Expiration { get; set; }

    public override string ToString()
    {
        return Reference + "//" + Expiration.Year + "/" + Expiration.Month;
    }
}

Notes

  • Automatically implemented getters are readonly.
  • You can apply the readonly modifier to overridden System.Object members.
  • You can apply the readonly modifier to instance methods, properties and indexers.
  • You can apply the readonly modifier to static fields (but not properties or methods).

More information