Read the syntax
Keep equality and hash codes consistent when objects represent the same logical value.
Equals and GetHashCode use the same OrdinalIgnoreCase rule.
What it is and why to use it
Two separate objects can represent the same logical identifier. IEquatable<T> supplies a strongly typed equality operation used by default generic equality comparers. A class implementing value equality should also override object.Equals and GetHashCode consistently. Records already provide generated value equality that is often sufficient for simple data.
How it works
Equal values must produce equal hash codes. Unequal values may collide, so a hash is not a unique identifier. Hash-based collections use both hashing and equality. Keep equality-defining data stable while an object is a dictionary key or set member. A supplied IEqualityComparer can define an external policy without changing the type itself.
Common mistakes and limitations
Do not override Equals while leaving incompatible hashing. Do not persist runtime hash codes as stable IDs. Do not mutate the fields that determine a key’s hash after insertion. If equality is a complicated hierarchy-dependent rule, prefer a simpler domain design or use generated record semantics where appropriate.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
sealed class Key : IEquatable<Key> { /* Equals and GetHashCode */ }Examples
Deduplicate logical identifiers
Define case-insensitive equality for a domain that explicitly permits case-insensitive keys.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var keys = new HashSet<Key> { new("PHP"), new("php") };
Console.WriteLine(keys.Count);
sealed class Key(string value) : IEquatable<Key> {
public string Value { get; } = value;
public bool Equals(Key? other) => other is not null && StringComparer.OrdinalIgnoreCase.Equals(Value, other.Value);
public override bool Equals(object? obj) => obj is Key other && Equals(other);
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
}
- The two instances have different identities but equal domain values under the chosen comparer.
- Equals and GetHashCode use the same OrdinalIgnoreCase rule.
- HashSet keeps one logical key. The read-only Value property prevents ordinary mutation of equality data after construction.
- Expected output: 1
- Use the same data and comparison policy for equality and hashing.
Use an external equality policy instead
Select a comparer for a collection of existing string values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var exact = new HashSet<string>(StringComparer.Ordinal) { "PHP", "php" };
var folded = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "PHP", "php" };
Console.WriteLine(exact.Count);
Console.WriteLine(folded.Count);
- The first set treats uppercase and lowercase as different ordinal values.
- The second set uses case-insensitive ordinal equality and retains one.
- The string type itself is unchanged. An external comparer is useful when a specific collection needs a policy that is not universal for the domain.
- Expected output: 2 1
- Use the same data and comparison policy for equality and hashing.
Best practices
- Use the same data and comparison policy for equality and hashing.
- Keep hash-key state stable after insertion.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference