Skip to content

Record structs C# 10.0code reduction

Allow records to be value type structs.

Record structs bring the power of the records C# 9.0 feature from classes to structs.

While structs already had value equality, it came from ValueType.Equals which can fall back to slow reflection, and they did not provide ==, a readable ToString or deconstruction. This feature brings all that to struct types.

Code ​

csharp
readonly record struct Money(decimal Amount, string Currency);
csharp
readonly struct Money : IEquatable<Money>
{
    public decimal Amount { get; }
    public string Currency { get; }

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

    public void Deconstruct(out decimal amount, out string currency)
    {
        amount = Amount;
        currency = Currency;
    }

    public override bool Equals(object obj) => obj is Money other && Equals(other);
    public bool Equals(Money other) => Amount == other.Amount && Currency == other.Currency;
    public override int GetHashCode() => HashCode.Combine(Amount, Currency);
    public override string ToString() => $"Money {{ Amount = {Amount}, Currency = {Currency} }}";

    public static bool operator ==(Money left, Money right) => left.Equals(right);
    public static bool operator !=(Money left, Money right) => !left.Equals(right);
}

Notes ​

  • The positional properties of a record struct are read-write by default, unlike a record class where they are init-only
  • To become immutable you should use readonly record struct

More information ​

Powered by Intracia