Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How to Overload the == Operator in C#

How to overload == in C# for classes and structs, including null-safe patterns and the companion methods you need.

~8 min readC#
#C# equality#operator overloading#value types#reference types
Illustration of two C# code blocks merging into a single equal sign, representing operator overloading.

Overloading the == operator in C# lets you define what equality means for your own types. It is a common way to customize equality, but it is only reliable when Equals and GetHashCode are updated consistently. The following sections cover the syntax, the required companion methods, null handling, and the practical pitfalls to avoid.

By default, == uses reference equality for classes. For an ordinary custom struct, no == operator is available until you define one. In many cases, you need a rule other than reference equality—for example, two Person objects might be equal when their Id values match, regardless of whether they point to the same memory location. To make that happen, you overload == and usually also override Equals and GetHashCode.

This article focuses on the correct syntax, the required companion methods, and the runtime behavior that makes overloading == work reliably. It covers when to use it, when to avoid it, and the subtle performance and compatibility implications that often surprise developers.

The Basic Syntax for Overloading ==

To overload ==, define a static operator method inside the type. The method must take two parameters of the containing type and return a bool.

csharp
public struct Money { public decimal Amount { get; } public string Currency { get; } public Money(decimal amount, string currency) { Amount = amount; Currency = currency; } public static bool operator ==(Money left, Money right) { return left.Amount == right.Amount && left.Currency == right.Currency; } public static bool operator !=(Money left, Money right) { return !(left == right); } }

This code lets you compare Money instances with == and != in a natural way. The != operator is not automatically derived from ==; you must define it explicitly. The overload is a static method, not an extension method—you cannot overload operators with extension methods. This minimal example shows the syntax; a production implementation should also override Equals and GetHashCode as shown later.

Why You Must Override Equals and GetHashCode

When you overload ==, you introduce a new definition of equality that may conflict with the base implementation of Object.Equals. In C#, == is not virtual, but Equals is. Many framework code paths—Dictionary<TKey, TValue>, HashSet<T>, and List<T>.Contains—rely on Equals rather than ==. If your == says two objects are equal but Equals says they are not, behavior becomes inconsistent and confusing.

For value types, the default ValueType.Equals uses reflection and can be slow. Overriding it lets you provide faster, semantically correct equality. For reference types, the default object.Equals checks reference equality. If your == overload defines value equality, then Equals should match that same logic.

The compiler does not force you to override these methods, but omitting them leads to subtle bugs. For example, a HashSet<T> will not treat two objects as equal if Equals is not overridden, even if == returns true. That inconsistency can break collection behavior, so the rule is: overload == only if you also override Equals and GetHashCode.

Here is a corrected version for a reference type:

csharp
public class Person { public string Id { get; } public string Name { get; } public Person(string id, string name) { Id = id; Name = name; } public override bool Equals(object obj) { return obj is Person other && Id == other.Id; } public override int GetHashCode() { return Id.GetHashCode(); } public static bool operator ==(Person left, Person right) { if (left is null) return right is null; return left.Equals(right); } public static bool operator !=(Person left, Person right) { return !(left == right); } }

The == operator here delegates to Equals to ensure consistency. It also handles null correctly. Notice that we use is null to avoid the overloaded == inside the operator itself, which would otherwise cause infinite recursion.

Handling Nulls in the == Operator

Null handling is the most error-prone part of overloading ==. If you write a naive comparison that dereferences a parameter without checking for null, you get a NullReferenceException when one side is null. Worse, if you call the overloaded == inside the operator itself, you trigger infinite recursion.

csharp
// Dangerous: calls itself recursively public static bool operator ==(Person left, Person right) { return left == right; }

Always compare with ReferenceEquals or use pattern matching with is null for null checks. For value types, nullability is handled by lifted operators: Nullable<T> lifts a user-defined == so that S? values can be compared. The lifted operator returns false when exactly one side is null and checks the underlying values when both sides have values.

If you are working with a class, the safest pattern is:

csharp
public static bool operator ==(Person left, Person right) { if (left is null) return right is null; return left.Equals(right); }

This returns true when both are null and false when exactly one is null. In C# equality, null equals null is a sensible convention.

When to Overload == for Value Types vs Reference Types

For value types, overloading == is a strong choice because the default ValueType.Equals can be slow and may not reflect the equality rule you need. For example, a struct representing a Money amount should compare by numeric value and currency, not merely by the default field-by-field behavior.

For reference types, the decision is less clear-cut. If your type is an entity with an identity (like a database row with an Id), overriding == to compare by that Id can be convenient, but it changes the semantics of equality for the entire lifetime of the object. In many designs, reference equality is the correct default for mutable classes. Using value equality for mutable objects can cause collections to break if the object changes after being added to a dictionary.

Type KindDefault behaviorWhen overloading makes sense
classReference equalityImmutable value-like objects (e.g., DateRange, Coordinates)
structNo default == for ordinary custom structs; Equals uses field-by-field reflectionAny struct where equality should be fast or semantic
record (C# 9+)Compiler-generated value equalityUsually not needed unless custom logic is required

The table clarifies the typical use cases. For records, the compiler already implements value equality, so adding your own operator overload is only necessary when you want to change the default behavior, such as ignoring certain properties.

Performance and Runtime Considerations

Overloading == can improve performance by avoiding reflection-based equality checks, but it can also introduce hidden costs. When you write left == right inside the operator, be wary of recursion. Also, if the operator performs complex calculations, like normalizing strings, it may be slower than a simple reference comparison.

For value types, the JIT can often inline simple operator methods, making == nearly as fast as a direct field comparison. For reference types, the cost is primarily the method call overhead, which is usually negligible compared with the actual comparison work.

One important performance concern is consistency with GetHashCode. If two objects are equal via ==, they must produce the same hash code. If not, hashtable-based collections become incorrect. A common mistake is to compare all fields in == but use only one field in GetHashCode. That is acceptable if that field determines equality, but if equality can be true for objects with different hash codes, you have a bug.

Another operational consideration is Nullable<T>. For a struct S, S? lifts a user-defined ==, so the compiler supplies null handling; when both operands are non-null, your operator is called. Test comparisons through S? as well as S to avoid surprises.

Common Pitfalls and How to Avoid Them

The most common pitfalls when overloading == are:

  1. Forgetting to overload != – The compiler does not infer != from ==. Without it, you get a compile-time error if you try to use !=.
  2. Using the overloaded operator inside itself – This causes infinite recursion. Use ReferenceEquals or is null for null checks.
  3. Inconsistent equality helpers – If == says equal but Equals says not equal, collections break.
  4. Bad GetHashCode – If GetHashCode is not consistent with ==, Dictionary and HashSet will misbehave.
  5. Overloading for mutable reference types – If the object changes after being added to a collection, equality may change unexpectedly.

For example, this code contains a subtle bug:

csharp
public static bool operator ==(Person left, Person right) { return left.Id == right.Id; // No null check }

If left is null, this throws. The corrected version should handle null explicitly. Also, if Id is a string, the == on strings already handles nulls, but left itself could be null.

Best Practices for Overloading == in Public APIs

When you design a public API, overloading == affects how consumers perceive your type. Always document the equality semantics. If the type is intended to be used as a key in a dictionary, make sure the hash code is stable and does not depend on mutable state.

Consider implementing IEquatable<T> as well. Generic collection methods can then call the strongly typed Equals(T) directly, which avoids the boxing and type cast that come with Equals(object). Here is an example for a class:

csharp
public class Money : IEquatable<Money> { public decimal Amount { get; } public string Currency { get; } public bool Equals(Money other) { if (other is null) return false; return Amount == other.Amount && Currency == other.Currency; } public override bool Equals(object obj) => Equals(obj as Money); public override int GetHashCode() => HashCode.Combine(Amount, Currency); public static bool operator ==(Money left, Money right) { return left?.Equals(right) ?? (right is null); } public static bool operator !=(Money left, Money right) => !(left == right); }

Note the use of HashCode.Combine for producing a hash code, and the null-conditional ?. to avoid explicit null checks in the class-based == operator. This pattern is concise and correct for a class. For a struct, null checks are not needed because a non-nullable struct cannot be null.

Compatibility and Language Version Considerations

HashCode.Combine is a .NET library method introduced in .NET Core 2.1 and .NET Standard 2.1, not a C# language feature. If you target .NET Framework, you may need to combine hash codes manually.

Records change the picture in C# 9 and later. They synthesize value-equality members. If you add a custom == to a record, make sure it agrees with the synthesized Equals and GetHashCode; otherwise collection behavior can be inconsistent.

The same rules apply in older C# versions that do not use records: overload ==, override Equals and GetHashCode, and implement IEquatable<T> when appropriate.

Advanced: Operator Overloading and Inheritance

Operator overloads are static methods and are not virtual. This means that if a base class declares an overloaded == and a derived class does not declare its own, the base implementation can be used. This behavior can be surprising when derived types add fields that should participate in equality.

csharp
public class Base { public static bool operator ==(Base a, Base b) { ... } public static bool operator !=(Base a, Base b) { ... } } public class Derived : Base { // If Derived does not declare its own operators, the base operators are used. }

If you compare two Derived objects with ==, the base operator runs, which may ignore derived-specific fields. To handle derived types properly, you must either avoid overloading == in the base type or cast inside the operator and handle type mismatches. The recommended approach is to avoid overloading == in a non-sealed class unless you are prepared for that complexity.

Instead, prefer to implement IEquatable<T> on the derived types and let the base class provide a virtual Equals that derived classes can override. The == operator should delegate to Equals, as shown earlier, so that polymorphism works correctly.

Choosing the Right Equality Approach

Overloading == is not always the best solution. If you only need to compare objects for hashing, implementing IEquatable<T> and GetHashCode without overloading == may be sufficient. If you need == syntax on a concrete type, overloading the operator is required, because IEquatable<T> supplies only an Equals method.

The decision criteria are:

  • Use == overload when you want natural syntax for equality comparisons in your domain.
  • Use IEquatable<T> when you need fast equality checks in collections, particularly to avoid boxing for structs.
  • Use record types when you want value equality with minimal code for immutable data.

In practice, many developers combine these: overload == and implement IEquatable<T> to keep all equality paths consistent.

By following the rules outlined in this article, you can overload == safely and efficiently, avoiding the common bugs that arise from inconsistent equality implementations.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.