Module 1 · Equality, comparers and reliable keys · Lesson 1 of 14
==, Equals and ReferenceEquals in C#
C# ==, Equals and ReferenceEquals answer different equality questions. Learn their defaults and why strings, boxing and generic code can surprise you.
What this lesson teaches
In the string example below, changing the expressions from string to object changes which == comparison runs. The instance method Equals can use the actual object's equality implementation. ReferenceEquals asks only whether two references identify the same object.
After this lesson, you can explain:
- Which comparisons use object identity and which compare contents.
- Why changing a variable's declared type can change
==. - Why
ReferenceEquals(5, 5)returnsfalse. - Which comparison to use in generic code or when either argument might be
null. - When a custom type should define
==.
Each program below runs independently. Predict its results before running it.
Two meanings of equality
Reference equality, also called identity, means that two references point to the exact same object. Two separately created customer objects do not have reference equality, even if every property matches.
Value equality means that two values match according to the type's comparison rules. Those rules decide which contents matter. For strings, the characters matter; the identity of the string objects does not.
There are also two different ways C# chooses comparison code:
- The compile-time type, also called the static type, is the type the compiler sees for an expression.
- The runtime type is the type of the object that an expression refers to while the program runs.
For example, in object item = "report", the variable's compile-time type is object, but its object's runtime type is string.
A virtual method lets a type provide its own implementation through an override. The instance method object.Equals(object) is virtual. A type can therefore replace its inherited equality behavior.
An operator overload gives an operator such as == an implementation for particular operand types. Unlike a virtual method call, ordinary == does not search the runtime objects for a better implementation.
What == and Equals do by default
Start with types that do not define custom equality: a plain class, a plain struct, a record and two tuples. See Microsoft's equality comparison guide for the default rules for classes, structs and tuples.
For string comparison rules, including ordinal and case-sensitive comparisons, see Microsoft's best practices for comparing strings.
Guess which lines print True:
using System;
var first = new Customer { Id = 7 };
var second = new Customer { Id = 7 };
var alias = first;
Console.WriteLine($"class ==: {first == second}");
Console.WriteLine($"class Equals: {first.Equals(second)}");
Console.WriteLine($"class alias ==: {first == alias}");
var point1 = new Point { X = 4 };
var point2 = new Point { X = 4 };
Console.WriteLine($"struct Equals: {point1.Equals(point2)}");
// point1 == point2 would not compile: Point declares no == operator.
var label1 = new Label("Ready");
var label2 = new Label("Ready");
Console.WriteLine($"record ==: {label1 == label2}");
Console.WriteLine($"record Equals: {label1.Equals(label2)}");
var tuple1 = (Code: 7, Text: "Ready");
var tuple2 = (Number: 7, Name: "Ready");
Console.WriteLine($"tuple ==: {tuple1 == tuple2}");
public sealed class Customer
{
public int Id { get; set; }
}
public struct Point
{
public int X;
}
public sealed record Label(string Text);class ==: False class Equals: False class alias ==: True struct Equals: True record ==: True record Equals: True tuple ==: True
first and second refer to separate customer objects. Matching Id properties do not change the class's default rules, so both comparisons return False. The alias comparison returns True because it compares one object with itself.
The two points compare equal through Equals because their fields match. Uncommenting the invalid comparison would produce compiler error CS0019: this plain struct has no applicable == operator.
The compiler generates value-based equality members for the record, so both record comparisons return True. The tuples also compare equal. Tuple element names are not part of the comparison; positions and element values are.
The mistake to avoid. Do not assume == and Equals are interchangeable, or that every struct supports both. The type's equality implementation determines what is available and what it means.
In an interview, say: “== is an operator chosen at compile time; Equals(object) is a virtual method. Plain classes default to reference equality for both. Plain structs have field-value Equals but no predefined ==. Strings provide value-based comparisons, and records get generated equality members.”
Why equal strings can compare false with ==
The declared types of the operands matter. Two expressions typed as string use string's text-comparison operator. Two expressions typed as object use reference comparison instead.
An interface-typed expression is similar here: comparing two interface variables with ordinary == tests their references. Calling Equals still reaches the underlying object's implementation.
This example creates two separate strings deliberately. That makes identity different from text equality.
using System;
string left = new string(new[] { 'O', 'K' });
string right = new string(new[] { 'O', 'K' });
object objectLeft = left;
object objectRight = right;
IComparable interfaceLeft = left;
IComparable interfaceRight = right;
Console.WriteLine($"string ==: {left == right}");
Console.WriteLine($"object ==: {objectLeft == objectRight}");
Console.WriteLine($"object Equals: {objectLeft.Equals(objectRight)}");
Console.WriteLine($"interface ==: {interfaceLeft == interfaceRight}");
Console.WriteLine($"interface Equals: {interfaceLeft.Equals(interfaceRight)}");
Console.WriteLine($"same object: {ReferenceEquals(left, right)}");string ==: True object ==: False object Equals: True interface ==: False interface Equals: True same object: False
The object and interface == comparisons return False: there are two objects, not one.
Both Equals calls return True. The receiver is the object a method is called on: the expression before the dot supplies it. Here, that object is a string, and string overrides Equals(object) to compare text.
flowchart TD
A["Two separate strings: OK"] -->|compared with| B["string =="]
A -->|compared with| C["object =="]
B -->|compares text| D["True"]
C -->|compares identity| E["False"]
The diagram shows how the same objects produce different results when the operands have different compile-time types.
No string contents changed when we assigned the references to object variables. Only the operator available to those expressions changed. Microsoft's equality comparison guide covers these defaults and interface comparisons.
The mistake to avoid. Do not inspect only the objects being compared. For ==, inspect the types of the expressions at the comparison itself.
In an interview, say: “Two equal strings can compare false with == when the operands are typed as object or an interface. That comparison uses reference equality. Calling the overridden Equals on those string objects still compares their text.”
Why == is risky in generic code
A generic method must compile using what its constraints promise. A generic constraint limits which types a caller may supply and tells the compiler which operations are available.
With where T : class, the compiler knows that T is a reference type. It does not select string's == later just because a particular call supplies strings. The == in that method uses reference equality. The constraints on type parameters guide explains this behavior for the where T : class constraint.
EqualityComparer<T>.Default provides the default equality comparison for T. It uses IEquatable<T> when available, otherwise the type's Equals implementation. IEquatable<T> is an interface through which a type provides an Equals(T) method for comparing its own type.
using System;
using System.Collections.Generic;
string left = new string(new[] { 'O', 'K' });
string right = new string(new[] { 'O', 'K' });
Console.WriteLine($"generic ==: {SameReference(left, right)}");
Console.WriteLine($"generic comparer: {SameValue(left, right)}");
Console.WriteLine($"object.Equals: {object.Equals(left, right)}");
static bool SameReference<T>(T left, T right) where T : class
{
return left == right;
}
static bool SameValue<T>(T left, T right)
{
return EqualityComparer<T>.Default.Equals(left, right);
}generic ==: False generic comparer: True object.Equals: True
SameReference returns False, even though the caller supplied strings with equal text. Its body was compiled as a reference comparison.
SameValue returns True because the default string comparer compares text. The static object.Equals call also returns True; its null-handling behavior is covered below.
Use the default equality comparer when a generic method should respect the type's normal equality rules. The name does not promise value equality for every type: a plain class still has its default identity-based equality.
The mistake to avoid. Do not expect where T : class to make == choose a different operator for each runtime type. That constraint permits reference comparison; it does not request each type's equality policy.
In an interview, say: “In a generic method constrained with where T : class, a == b uses reference equality, even for strings. For the type's default equality rules, I use EqualityComparer<T>.Default.Equals(a, b). object.Equals(a, b) is another option.”
Boxing, ReferenceEquals and numeric comparisons
Boxing wraps a value-type value in an object so that it can be used through an object reference. Separate boxing operations create separate objects.
ReferenceEquals always tests identity, regardless of a type's Equals override or == overload. When you pass two value-type arguments directly, each argument is boxed separately. So ReferenceEquals on two non-null value-type arguments always returns false, even when the values match.
using System;
Console.WriteLine($"ReferenceEquals ints: {ReferenceEquals(5, 5)}");
Console.WriteLine($"boxed ==: {(object)5 == (object)5}");
Console.WriteLine($"boxed Equals: {((object)5).Equals((object)5)}");
object box = 5;
Console.WriteLine($"same box: {ReferenceEquals(box, box)}");
Console.WriteLine($"int and long ==: {5 == 5L}");
Console.WriteLine($"int and long Equals: {5.Equals(5L)}");ReferenceEquals ints: False boxed ==: False boxed Equals: True same box: True int and long ==: True int and long Equals: False
The first two lines return False. Each comparison involves two independently created boxes, so the references differ.
The boxed Equals comparison returns True. The left box contains an int, whose Equals implementation can compare it with another boxed int of the same value.
ReferenceEquals(box, box) returns True. Both arguments already refer to the same box; passing those references does not box the integer again.
The final two lines show a different distinction. The compiler converts the int 5 to long, then uses the long == operator to compare 5L with 5L. The result is True.
5.Equals(5L) returns False. A long cannot convert to int implicitly, so the compiler picks Equals(object). The long is boxed, and Int32.Equals(object) returns false because the box does not hold an int. An int (System.Int32) and a long (System.Int64) are different types. The Int32.Equals documentation explains this type check.
The mistake to avoid. Do not read ReferenceEquals(5, 5) as a comparison of the numbers. It compares two boxes. Also, do not assume numeric conversions used by == are repeated by Equals.
In an interview, say: “ReferenceEquals(5, 5) returns false because each argument is boxed separately. Two boxes can contain equal integers without being the same object. By contrast, comparing a variable holding one box with itself returns true.”
Use static object.Equals when either value might be null
An instance call needs a non-null receiver. The static method object.Equals(a, b) lets you compare two arguments without calling an instance method on a possible null.
The Object.Equals(Object, Object) documentation describes these rules:
- If both arguments are
null, it returnstrue. - If exactly one is
null, it returnsfalse. - If both refer to the same object, it returns
trueimmediately. - Otherwise, it calls
a.Equals(b).
#nullable enable
using System;
object? missing = null;
object? first = new string(new[] { 'O', 'K' });
object? second = new string(new[] { 'O', 'K' });
Console.WriteLine($"both null: {object.Equals(missing, null)}");
Console.WriteLine($"one null: {object.Equals(missing, first)}");
Console.WriteLine($"matching text: {object.Equals(first, second)}");
Console.WriteLine($"matching identity: {ReferenceEquals(first, second)}");
var probe = new EqualityProbe();
Console.WriteLine($"same reference: {object.Equals(probe, probe)}");
Console.WriteLine($"instance calls after same reference: {probe.Calls}");
Console.WriteLine($"different references: {object.Equals(probe, new EqualityProbe())}");
Console.WriteLine($"instance calls after different references: {probe.Calls}");
public sealed class EqualityProbe
{
public int Calls { get; private set; }
public override bool Equals(object? other)
{
Calls++;
return false;
}
public override int GetHashCode() => 0;
}both null: True one null: False matching text: True matching identity: False same reference: True instance calls after same reference: 0 different references: False instance calls after different references: 1
The matching-text comparison returns True through string's Equals override. ReferenceEquals returns False because the strings are separate objects.
The probe deliberately returns false from its instance Equals method and counts calls. Comparing the probe with itself still returns True, with zero instance calls. Comparing it with another probe returns False and raises the call count to one.
Static object.Equals does not invent a universal definition of equal contents. After its initial checks, it relies on the first object's equality implementation. The Object.Equals documentation describes both the instance and static forms.
The mistake to avoid. Do not replace object.Equals(a, b) with a.Equals(b) unless you know a is non-null. The instance call throws when its receiver is null.
In an interview, say: “object.Equals(a, b) handles nulls: two nulls are equal, and exactly one null is unequal. It returns true for identical references; otherwise it calls a.Equals(b). It respects that object's equality implementation.”
When should a type define ==?
For most classes, keep reference equality and do not overload ==. Overload it only for value-like types, often immutable ones, whose contents cannot change after construction. Use value-based equality when separate instances should be interchangeable because they represent the same value. Identity is often the right default when individual objects matter.
A record is a useful starting point for a data-focused type. The compiler generates matching equality members, avoiding the work of writing them individually.
A hash code is a number that dictionaries and hash sets use to narrow their search for a key. Whenever you override Equals, also override GetHashCode so that equal values get equal hash codes; the compiler warns (CS0659) if you do not. Equality and Hash-Code Contracts for Immutable C# Value Keys explains the full contract. See the Object.GetHashCode documentation for the equality requirement.
using System;
using System.Collections.Generic;
var first = new ProductCode("A17");
var second = new ProductCode("A17");
var prices = new Dictionary<ProductCode, decimal>();
prices[first] = 12.50m;
Console.WriteLine($"operator equality: {first == second}");
Console.WriteLine($"method equality: {first.Equals(second)}");
Console.WriteLine($"matching hash codes: {first.GetHashCode() == second.GetHashCode()}");
Console.WriteLine($"lookup with equal key: {prices.ContainsKey(second)}");
public sealed record ProductCode(string Text);operator equality: True method equality: True matching hash codes: True lookup with equal key: True
These separate record instances represent the same product code. The generated equality and hash-code members let the dictionary recognize second as equal to its stored key.
For a hand-written implementation, define == and != as a pair. Keep them consistent with Equals, and keep GetHashCode consistent with equality. A plain struct needs its own operators if you want to compare it with ==; record structs and tuples already provide operator comparisons.
The mistake to avoid. Do not add value-based == while leaving identity-based Equals or an inconsistent hash code. Ordinary comparisons and dictionary lookups could then disagree about the same two objects.
In an interview, say: “Most classes should not overload ==; they keep reference equality. I overload it only for types with value meaning, such as a money or a point type. When I do, I also define != and keep both consistent with Equals and GetHashCode. If I override Equals, I also override GetHashCode so equal objects have equal hash codes, and implement IEquatable<T> consistently.”
Check yourself
Two separately created strings contain the same text. Both variables are declared as object. What do a == b and a.Equals(b) return?
Show answer
Correct answer: C
The object-typed == comparison checks identity, so separate objects compare false. The Equals call reaches string's override and compares the matching text.
What does ReferenceEquals(5, 5) return, and why?
Show answer
Correct answer: C
Each int argument is independently boxed into an object. ReferenceEquals compares those two object identities, not the integers inside them.
Going deeper
Earlier we said Equals can use the actual object's implementation. That needs one qualification. Method overloads are methods with the same name but different parameter lists. The compiler first selects an overload using the expressions' compile-time types. Runtime selection then applies if the selected method is virtual.
This distinction matters for types such as StringBuilder. It has an Equals(StringBuilder) overload that compares contents, but it does not override object.Equals(object) to do that. Comparing through object therefore uses inherited identity-based equality. A typed Equals overload alone does not change what callers of object.Equals observe.
Generated record equality is not a recursive comparison of every object reachable from the record. It uses the equality rules of its members. A member whose type retains reference equality can therefore make two otherwise similar records unequal. For record inheritance rules, see equality in inheritance hierarchies.
For frequently compared custom structs, consider implementing IEquatable<T> and overriding Equals(object) consistently. The Object.Equals guidance recommends custom value-type equality implementations because default field comparison can involve reflection. Reflection is the ability to inspect a type and its members at runtime. Hand-written equality adds maintenance work, so keep all comparison entry points aligned.
Sources
- C# Equality comparisons - C# | Microsoft Learn: Default equality by type kind; plain struct operator availability; records and tuples; interface comparisons; identity and boxing; equality and hash-code consistency.
- Object.Equals Method (System) | Microsoft Learn: Virtual Equals behavior, static null-safe comparison, numeric type distinctions, reference-type design guidance, StringBuilder overload distinction, and custom value-type equality guidance.
- EqualityComparer<T>.Default Property (System.Collections.Generic) | Microsoft Learn: Default generic comparer selection, including IEquatable<T> support.
- Best practices for comparing strings in .NET: Further reading on ordinal and case-sensitive string comparisons.
- Constraints on type parameters - C# | Microsoft Learn: With where T : class, == and != on the type parameter test reference identity, even if the type argument overloads them.
- Int32.Equals Method (System): Why an int does not equal a boxed long.
- Object.GetHashCode Method (System): Equal objects must have equal hash codes.
- Records - C# reference: Further reading on equality in record hierarchies.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 30 Nov 2026 ·