Skip to content

Record structs C# 10.0code reduction

Allow records to be value type structs.

Record structs brings the power of the records feature from classes to structs.

While structs already had some of the convenience features of records - GetHashCode and Equality for example - they did it via reflection and did not provide other record convenience features like deconstruction. This feature brings all that to struct types.

Code

C#
readonly record struct Money
{
    public Decimal Amount { get; init; }
    public string Currency { get; init; }

    public Money(Decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }
}
C#
struct Money
{
    public Decimal Amount { get; private init; }
    public string Currency { get; private init; }

    public Money(Decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public override bool Equals(object obj)
    {
        return (obj is Money other) && Equals(other);
    }

    public bool Equals(Money other)
    {
        return Amount == other.Amount && Currency == other.Currency;
    }

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 23 + Amount.GetHashCode();
        if (Currency != null) hash = hash * 23 + Currency.GetHashCode();
        return hash;
    }
}

Notes

  • record struct is not immutable by default unlike record class
  • To become immutable you should use readonly record struct

More information