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 structare read-write by default, unlike arecord classwhere they are init-only - To become immutable you should use
readonly record struct