A class uses reference equality by default: two objects with identical property values are normally unequal unless Equals is overridden. A record supplies value-based equality across its equality components. Whenever Equals says two values are equal, GetHashCode must return the same hash code. The reverse is not required because collisions are possible. Keys must also remain logically immutable while stored in a Dictionary or HashSet; changing a field used by equality can make an entry impossible to find. For a class, implement IEquatable<T>, override object.Equals, and combine the same fields in GetHashCode: ```csharp public sealed class ProductKey : IEquatable<ProductKey> { public required string Sku { get; init; } public required int OutletId { get; init; } public bool Equals(ProductKey? other) => other is not null && OutletId == other.OutletId && StringComparer.OrdinalIgnoreCase.Equals(Sku, other.Sku); public override bool Equals(object? obj) => Equals(obj as ProductKey); public override int GetHashCode() => HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Sku), OutletId); } ``` A concise alternative is `public sealed record ProductKey(string Sku, int OutletId);`. Use an explicit comparer when equality rules, such as case-insensitive text, differ from the type's defaults.
Prince Yadav · · 0 likes