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

Equality rules decide whether two objects are "the same", and hashing decides which bucket they go into in a Dictionary or HashSet. The two must agree. Classes (default) - Reference equality: two different instances with identical data are not equal. - GetHashCode is based on object identity. Records - Value equality is generated by the compiler: all properties (and the runtime type) must be equal. - GetHashCode is generated from the same members, so equal records have equal hashes. Overriding equality in a class — the contract: - If a.Equals(b) is true, a.GetHashCode() must equal b.GetHashCode(). - Equals must be reflexive, symmetric and transitive, and handle null. - Implement IEquatable<T>, override Equals(object) and GetHashCode together, and usually == and != as well. public sealed class Sku : IEquatable<Sku> { public string Code { get; } public Sku(string code) => Code = code.ToUpperInvariant(); public bool Equals(Sku? other) => other is not null && Code == other.Code; public override bool Equals(object? obj) => Equals(obj as Sku); public override int GetHashCode() => Code.GetHashCode(); } How mistakes break dictionaries and sets 1. Overriding Equals but not GetHashCode: equal objects land in different buckets, so ContainsKey returns false and duplicates appear in a HashSet. 2. Mutating a key after insertion: if a property used in GetHashCode changes, the object sits in the wrong bucket and can no longer be found or removed. This is why keys should be immutable — records with init-only properties help, but a record containing a mutable List<T> compares the list by reference and can still be changed. 3. Inconsistent comparisons, such as case-insensitive Equals with a case-sensitive hash code. 4. Including volatile data (timestamps, IDs assigned after saving) in equality for entities. Other tips: use StringComparer.OrdinalIgnoreCase for case-insensitive string keys, use HashCode.Combine(a, b) for multi-field hashes, and remember EF Core entities usually rely on identity (primary key), not value equality.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics