Skip to content

Commit 13736d9

Browse files
BillWagnerCopilotCopilotwadepickett
authored
[Everyday C#] Fundamentals: Equality comparisons (dotnet#54849)
* [Everyday C#] Phase E, PR 14b: Type system: equality Add fundamentals concept article on object equality for classes, structs, records, and tuples. Covers value equality vs. reference equality, Equals/==/ReferenceEquals semantics, IEquatable<T> implementation pattern, and record compiler-generated equality. Backed by a net10.0 snippet project (0 warnings, 0 errors). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5dca83ef-a274-4737-96d5-a311bfe58550 * [Everyday C#] Move equality to expressions Relocate the Equality fundamentals article and snippets from Type system to the new Expressions folder, and update the TOC and relative links for the new location. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3 * Address equality article review feedback Clarify default equality behavior, operator terminology, and manual value equality guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3 * Tighten struct equality guidance Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3 * Clarify manual equality guidance Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3 * Deemphasize IEquatable Deemphasize the value of IEquatable<T> throughout the article. * Deemphasize IEquatable in equality article Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3 * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Yet another editing pass Run another edit pass on this PR. * lint * Restructure for a better organization This organization of the material works much better. * Apply suggestions from code review Co-authored-by: Wade Pickett <wpickett@microsoft.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Wade Pickett <wpickett@microsoft.com> Copilot-Session: 5dca83ef-a274-4737-96d5-a311bfe58550 Copilot-Session: bc6b7895-3b18-45ff-99de-540618819cb3
1 parent 1d30bf7 commit 13736d9

4 files changed

Lines changed: 238 additions & 0 deletions

File tree

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
title: "C# Equality comparisons"
3+
description: Learn how C# compares values and references with ==, !=, Equals, GetHashCode, and ReferenceEquals for classes, structs, records, and tuples.
4+
ms.date: 07/22/2026
5+
ms.topic: concept-article
6+
ai-usage: ai-assisted
7+
---
8+
9+
# C# Equality comparisons
10+
11+
> [!TIP]
12+
> This article is part of the **Fundamentals** section for developers who already know at least one programming language and are learning C#. If you're new to programming, start with the [Get started](../../tour-of-csharp/tutorials/index.md) tutorials first.
13+
>
14+
> **Coming from another language?** In Java, `==` on objects and JavaScript `===` on objects test identity, not content. C# classes work the same way by default. In Python, `==` calls `__eq__` and tests content by default , similar to how C# [records](../types/records.md) compare. C# [structs](../types/structs.md) also compare by value when you call `Equals`.
15+
16+
C# distinguishes two kinds of equality. *Value equality* means two instances are equal when their data matches. *Reference equality* means two variables are equal only when they point to the same object in memory. This condition is also called *identity*. The kind of type gives you the best first clue about the default equality behavior: value types usually compare data, and reference types usually compare identity. Defaults aren't destiny, but that mental model prevents subtle bugs where two objects that look identical aren't considered equal, or where a mutation through one variable silently changes what another variable sees.
17+
18+
## Value types, reference types, and equality defaults
19+
20+
Every type in C# is either a *value type* or a *reference type*. A *value type* holds its data directly in the variable. A *reference type* holds a reference to an object. When you assign a reference-type variable to another variable, both variables refer to the same object. This article uses that distinction as a quick refresher. For more information about value types and reference types, see [Type system overview](../types/index.md#value-types-and-reference-types).
21+
22+
The default equality behavior usually follows the kind of type:
23+
24+
- **Built-in numeric types and [enums](../types/enums.md)** are value types. Two `int` variables are equal when their numeric values match.
25+
- **[Structs](../types/structs.md)** are value types. A plain `struct` uses value equality when you call <xref:System.Object.Equals*>.
26+
- **[Tuples](../types/tuples.md)** are value types. Two tuples are equal when all their element values match.
27+
- **[Classes](../types/classes.md)** are reference types. A plain class uses reference equality, so `==` and <xref:System.Object.Equals*> test whether two variables point to the same object.
28+
29+
A plain class shows reference equality. Two separate objects with the same data aren't equal, but two variables that refer to the same object are equal:
30+
31+
:::code language="csharp" source="snippets/equality/Program.cs" ID="ClassEquality":::
32+
33+
A plain `struct` shows value equality through <xref:System.Object.Equals*>. Two struct instances are equal when their fields match:
34+
35+
:::code language="csharp" source="snippets/equality/Program.cs" ID="StructEquality":::
36+
37+
Plain structs don't get a predefined `==` operator. Writing `p1 == p2` on a plain struct compiles only if the struct declares its own `operator ==`. If you need operator comparisons for a struct, define `==` and `!=` as a pair and keep them consistent with <xref:System.Object.Equals*> and <xref:System.Object.GetHashCode*>.
38+
39+
Tuples are value types too. Two tuples are equal when every element value matches. Element names in a named tuple are a compile-time convenience and aren't considered during comparison. Only positions and values matter:
40+
41+
:::code language="csharp" source="snippets/equality/Program.cs" ID="TupleEquality":::
42+
43+
For more information about tuple syntax and deconstruction, see [Tuples and deconstruction](../types/tuples.md).
44+
45+
## Types can define different equality semantics
46+
47+
Defaults aren't destiny. Some types define equality semantics that differ from the type-kind default, and your own types can do the same when their data should determine equality.
48+
49+
Common exceptions and customizations include:
50+
51+
- **[Records](../types/records.md)** generate value equality and include `==`/`!=` operators. The next section shows how the `record` modifier gives value equality to both record classes and record structs.
52+
- **Strings** are classes, but `==` and <xref:System.Object.Equals*> compare string content, not identity.
53+
- **Your own classes and structs** can define value equality when their data should determine equality.
54+
55+
Equality is woven through these related members:
56+
57+
- `==`: the equality operator. Most types use this as the primary equality check. Its behavior depends on whether the type has a built-in or user-defined `==` operator.
58+
- `!=`: the inequality operator. When a type defines a user-defined `==` operator, it must also define `!=`.
59+
- <xref:System.Object.Equals*>: a virtual method inherited by every type. You can override it to change equality semantics for a type.
60+
- <xref:System.Object.GetHashCode*>: a virtual method used by hash-based collections. When two values are equal, their hash codes must also be equal.
61+
- <xref:System.Object.ReferenceEquals*>: a static method that always tests identity.
62+
63+
## Use records for value equality
64+
65+
Use the `record` modifier to give a data-focused type value equality when the type can be a record. The compiler generates <xref:System.Object.Equals*>, <xref:System.Object.GetHashCode*>, and `==`/`!=` members that compare every declared property value.
66+
67+
A `record class` is still a reference type, but it compares values instead of identity:
68+
69+
:::code language="csharp" source="snippets/equality/Program.cs" ID="RecordEquality":::
70+
71+
<xref:System.Object.ReferenceEquals*> confirms that `person1` and `person2` are different objects in memory, while `==` and <xref:System.Object.Equals*> return `True` because the compiler-generated equality compares property values.
72+
73+
The same compiler generation applies to `record struct` types:
74+
75+
:::code language="csharp" source="snippets/equality/Program.cs" ID="RecordStructEquality":::
76+
77+
Record types generate the whole equality set for their own type. Both `record class` and `record struct` types override <xref:System.Object.Equals*> and <xref:System.Object.GetHashCode*>. They also generate `==` and `!=` operators, plus a typed `Equals` method for the record type. Unlike a plain `struct`, a `record struct` therefore supports `==` and `!=` automatically. For more information about record types and their equality semantics, see [Records](../types/records.md#value-equality).
78+
79+
## Implement equality yourself when a type can't be a record
80+
81+
> [!IMPORTANT]
82+
> This section shows how to implement by hand the equality behavior that the compiler generates when you add `record` to a type. If your type can be a record, use `record` instead. It generates all these members for you. Implement them manually only when your type can't be a record.
83+
84+
When a class or struct represents a value, such as a color or a measurement, the equality members for that type must agree. The easiest way to achieve this consistency is to declare the type as a `record`. If the type can't be a record, such as when it must derive from a non-record class, implement the equality members yourself. The language enforces that user-defined `==` and `!=` operators must be declared as a pair. If you provide those operators, compiler warning [CS0660](../../language-reference/compiler-messages/overloaded-operator-errors.md#equality-operators) means the type also needs an <xref:System.Object.Equals*?displayProperty=nameWithType> override. Warning [CS0661](../../language-reference/compiler-messages/overloaded-operator-errors.md#equality-operators) means the type also needs an <xref:System.Object.GetHashCode*?displayProperty=nameWithType> override.
85+
86+
In a complete manual implementation, provide these members:
87+
88+
- `==` and `!=` operators. Add them as a pair because the compiler requires a type that overloads one to overload the other.
89+
- An `override` of <xref:System.Object.Equals*>. This override changes equality semantics for the type and keeps object-level equality consistent.
90+
- An `override` of <xref:System.Object.GetHashCode*>. Objects that are equal must return the same hash code. Without this pairing, the type behaves incorrectly in hash-based collections such as `Dictionary<TKey,TValue>` or `HashSet<T>`. See <xref:System.Object.GetHashCode*> for guidance on a correct implementation.
91+
- Optionally, a typed `Equals` method by implementing <xref:System.IEquatable`1>. You often see this written as `Equals(T?)` in docs: `T` is a [type parameter](../types/generics.md), a placeholder for the current type, and `?` is a [nullable annotation](../null-safety/index.md) that says the argument can be `null`. This typed method can avoid extra conversions when callers already have the same type, but it's a secondary optimization.
92+
93+
The following example starts with the <xref:System.Object.Equals*> and <xref:System.Object.GetHashCode*> overrides, plus the optional typed `Equals` member, so you can see their effect before the `==` and `!=` operators are added. `HashCode.Combine` is a library helper that builds one hash code from the same values used by `Equals`:
94+
95+
:::code language="csharp" source="snippets/equality/Program.cs" ID="ColorDefinition":::
96+
97+
At this point, `Equals` reflects value equality, but `==` still tests identity for the class because the type hasn't declared `==` and `!=` operators. Plain structs likewise still don't have a predefined `==` operator unless you declare one:
98+
99+
:::code language="csharp" source="snippets/equality/Program.cs" ID="IEquatableUsage":::
100+
101+
Adding `==` and `!=` operators is the remaining step when you need operator comparisons. This article intentionally stops before the full operator implementation so the first pass can focus on the equality contract. The operator-focused follow-up shows the completed shape. For the operator syntax, see [Equality operators](../../language-reference/operators/equality-operators.md) in the language reference.
102+
103+
## Use `Object.ReferenceEquals` to test identity directly
104+
105+
<xref:System.Object.ReferenceEquals*> always tests identity regardless of how a type overrides <xref:System.Object.Equals*> or overloads `==`. Use it as an identity diagnostic when you need to confirm whether two variables point to the exact same object:
106+
107+
:::code language="csharp" source="snippets/equality/Program.cs" ID="ReferenceEqualsDemo":::
108+
109+
A common use is inside an `Equals` override to short-circuit the full comparison: when both arguments are the same reference, they're always equal without checking individual fields.
110+
111+
> [!NOTE]
112+
> Advanced detail: when variables are typed as an [interface](../types/interfaces.md), `==` checks whether the interface variables refer to the same object. A call to `Equals` still runs the underlying object's implementation.
113+
114+
## See also
115+
116+
- [Type system overview](../types/index.md)
117+
- [Classes](../types/classes.md)
118+
- [Structs](../types/structs.md)
119+
- [Records](../types/records.md)
120+
- [Tuples and deconstruction](../types/tuples.md)
121+
- [Equality operators (language reference)](../../language-reference/operators/equality-operators.md)
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// <ClassEquality>
2+
var order1 = new Order(42, "Shoes");
3+
var order2 = new Order(42, "Shoes");
4+
5+
Console.WriteLine(order1 == order2); // => False
6+
Console.WriteLine(order1.Equals(order2)); // => False
7+
Console.WriteLine(ReferenceEquals(order1, order2)); // => False
8+
9+
Order order3 = order1;
10+
Console.WriteLine(order1 == order3); // => True
11+
// </ClassEquality>
12+
13+
// <StructEquality>
14+
var pt1 = new Point(3, 4);
15+
var pt2 = new Point(3, 4);
16+
17+
Console.WriteLine(pt1.Equals(pt2)); // => True
18+
// </StructEquality>
19+
20+
// <RecordEquality>
21+
var person1 = new Person("Ada", "Lovelace");
22+
var person2 = new Person("Ada", "Lovelace");
23+
24+
Console.WriteLine(person1 == person2); // => True
25+
Console.WriteLine(person1.Equals(person2)); // => True
26+
Console.WriteLine(ReferenceEquals(person1, person2)); // => False
27+
// </RecordEquality>
28+
29+
// <RecordStructEquality>
30+
var dim1 = new Dimension(1920, 1080);
31+
var dim2 = new Dimension(1920, 1080);
32+
33+
Console.WriteLine(dim1 == dim2); // => True
34+
Console.WriteLine(dim1.Equals(dim2)); // => True
35+
// </RecordStructEquality>
36+
37+
// <TupleEquality>
38+
var t1 = (Name: "Grace", Role: "Engineer");
39+
var t2 = (Name: "Grace", Role: "Engineer");
40+
41+
Console.WriteLine(t1 == t2); // => True
42+
// </TupleEquality>
43+
44+
// <IEquatableUsage>
45+
var red1 = new Color(255, 0, 0);
46+
var red2 = new Color(255, 0, 0);
47+
48+
Console.WriteLine(red1.Equals(red2)); // => True
49+
Console.WriteLine(red1 == red2); // => False (no == overload; identity check)
50+
// </IEquatableUsage>
51+
52+
// <ReferenceEqualsDemo>
53+
var doc1 = new Document("Report");
54+
var doc2 = new Document("Report");
55+
var doc3 = doc1;
56+
57+
Console.WriteLine(ReferenceEquals(doc1, doc2)); // => False
58+
Console.WriteLine(ReferenceEquals(doc1, doc3)); // => True
59+
// </ReferenceEqualsDemo>
60+
61+
// ── Type declarations ────────────────────────────────────────────────────────
62+
63+
class Order(int id, string name)
64+
{
65+
public int Id { get; } = id;
66+
public string Name { get; } = name;
67+
}
68+
69+
struct Point(int x, int y)
70+
{
71+
public int X { get; } = x;
72+
public int Y { get; } = y;
73+
}
74+
75+
record Person(string First, string Last);
76+
77+
record struct Dimension(double Width, double Height);
78+
79+
// <ColorDefinition>
80+
class Color : IEquatable<Color>
81+
{
82+
public Color(int r, int g, int b)
83+
{
84+
R = r;
85+
G = g;
86+
B = b;
87+
}
88+
89+
public int R { get; }
90+
public int G { get; }
91+
public int B { get; }
92+
93+
public bool Equals(Color? other) =>
94+
other is not null && R == other.R && G == other.G && B == other.B;
95+
96+
public override bool Equals(object? obj) => obj is Color other && Equals(other);
97+
public override int GetHashCode() => HashCode.Combine(R, G, B);
98+
}
99+
// </ColorDefinition>
100+
101+
class Document(string title)
102+
{
103+
public string Title { get; } = title;
104+
}
105+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net10.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>

docs/csharp/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ items:
115115
href: fundamentals/tutorials/string-interpolation.md
116116
- name: Expressions and statements
117117
items:
118+
- name: Equality
119+
href: fundamentals/expressions/equality.md
118120
- name: Selection statements
119121
href: fundamentals/statements/selection.md
120122
- name: Iteration statements

0 commit comments

Comments
 (0)