wasAsked.

Explain the equality and hashing rules for C# classes and records, and how mistakes affect dictionaries and sets.

BrowserStack · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, C#, Software Engineering

Community answers

Posted by wasAsked editorial collection

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

Sign in to add your answer

Related interview topics