How to Compare Two Objects by Value with Equals in C#
Two Book objects with the same title and year are still two separate objects, so first.Equals(second) prints False until you tell C# what makes two books equal. Override Equals, and the same call prints True.
Every C# type has an Equals method, because every type inherits it from object. Microsoft's API reference describes it as: Determines whether two object instances are equal. For a class, it starts out comparing references, not values: If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.
For a class that holds data, you usually want something else, and the reference goes on: However, types often override the Equals method to implement value equality. Value equality means that two objects are equal when the values they hold are equal. This post overrides Equals in a small class, together with GetHashCode, which has to go with it.
Syntax
public override bool Equals(object? <obj>) =>
<obj> is <Type> <other> && <Value1> == <other>.<Value1> && <Value2> == <other>.<Value2>;
public override int GetHashCode() => HashCode.Combine(<Value1>, <Value2>);
bool <same> = <first>.Equals(<second>);
| Part | What it is |
|---|---|
override | Replaces the Equals or GetHashCode that your class inherits from object |
object? <obj> | The other object. Its type is object?, so it can be anything, even null |
<obj> is <Type> <other> | A declaration pattern. It's true when <obj> isn't null and is a <Type>, and then <other> holds it as a <Type> |
<Type> | Your class, such as Book |
<other> | A new variable for the other object, typed as your class |
<Value1> == <other>.<Value1> | Compares one value of this object with the same value of the other object. Add one comparison, joined with &&, for each value that decides equality |
HashCode.Combine(<Value1>, <Value2>) | Builds one hash code from the same values that Equals compares |
<first>.Equals(<second>) | Calls your override. It returns true when the values match |
<same> | The bool result |
The Example
A console app called EqualsByValue has a small Book class with a title and a year. It creates two books that are both Night Train from 2019, and a third book, Blue Sky from 2021. Then it compares them with Equals, with == and with object.ReferenceEquals, to show which of them look at the values.
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0.
Step 1: Create a Console App
dotnet new console -n EqualsByValue
cd EqualsByValue
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/EqualsByValue/EqualsByValue.csproj:
Determining projects to restore...
Restored /Users/you/source/EqualsByValue/EqualsByValue.csproj (in 45 ms).
Restore succeeded.
dotnet new console -n EqualsByValue creates a folder named EqualsByValue with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or EqualsByValue.csproj in Visual Studio.
Step 2: Write the Code
Replace everything in Program.cs. First the three books:
// Two books with the same title and year, and a third one that's different.
Book first = new("Night Train", 2019);
Book second = new("Night Train", 2019);
Book other = new("Blue Sky", 2021);
new("Night Train", 2019) creates a Book with that title and year. first and second hold the same values, but each new creates an object of its own.
Then the Equals calls:
// Equals compares the values, because Book overrides it.
Console.WriteLine($"first.Equals(second): {first.Equals(second)}");
Console.WriteLine($"first.Equals(other): {first.Equals(other)}");
first.Equals(second) calls the Equals that Book overrides further down, so it compares the titles and the years. first.Equals(other) compares Night Train from 2019 with Blue Sky from 2021. The extra spaces in the labels only line up the output.
Then == and object.ReferenceEquals:
// == on a class still asks whether both variables point to the same object.
Console.WriteLine($"first == second: {first == second}");
Console.WriteLine($"Same object: {object.ReferenceEquals(first, second)}");
Overriding Equals doesn't change ==. Microsoft's operator reference says it about a class that overrides Equals: Equals reflects value equality, but == still tests identity because no == operator has been declared yet. object.ReferenceEquals asks only whether both variables point to the same object. The equality guide: ReferenceEquals always tests identity regardless of how a type overrides Equals or overloads ==.
Then the Book class, at the end of the file:
class Book(string title, int year)
{
public string Title { get; } = title;
public int Year { get; } = year;
(string title, int year) after the class name takes the title and the year that new passes in, and the properties Title and Year keep them.
Then the Equals override:
// Two books are equal when their titles and years are equal.
public override bool Equals(object? obj) =>
obj is Book book && Title == book.Title && Year == book.Year;
obj is Book book is a declaration pattern. The C# reference: When a declaration pattern matches an expression, it assigns the variable to the converted expression result. When obj is a Book, book is that same object as a Book, and the two && comparisons check its title and year. When obj is null or something other than a Book, the pattern doesn't match and Equals returns false.
Last, GetHashCode:
// Objects that are equal must return the same hash code.
public override int GetHashCode() => HashCode.Combine(Title, Year);
}
The Equals reference sets the rule: Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly. The equality guide says why: When two values are equal, their hash codes must also be equal. HashCode.Combine(Title, Year) Combines two values into a hash code, in the words of its reference, so two books with the same title and year get the same hash code.
Step 3: Run It
Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:
dotnet run
first.Equals(second): True
first.Equals(other): False
first == second: False
Same object: False

first.Equals(second) printed True: both books are Night Train from 2019, and the override compared those values. first.Equals(other) printed False, because the title and the year differ. first == second printed False, and so did object.ReferenceEquals: first and second are still two separate objects, and that's all == checks on this class.
The Complete File

// Two books with the same title and year, and a third one that's different.
Book first = new("Night Train", 2019);
Book second = new("Night Train", 2019);
Book other = new("Blue Sky", 2021);
// Equals compares the values, because Book overrides it.
Console.WriteLine($"first.Equals(second): {first.Equals(second)}");
Console.WriteLine($"first.Equals(other): {first.Equals(other)}");
// == on a class still asks whether both variables point to the same object.
Console.WriteLine($"first == second: {first == second}");
Console.WriteLine($"Same object: {object.ReferenceEquals(first, second)}");
class Book(string title, int year)
{
public string Title { get; } = title;
public int Year { get; } = year;
// Two books are equal when their titles and years are equal.
public override bool Equals(object? obj) =>
obj is Book book && Title == book.Title && Year == book.Year;
// Objects that are equal must return the same hash code.
public override int GetHashCode() => HashCode.Combine(Title, Year);
}
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Comparing objects with Equals without overriding it | Without the two overrides, first.Equals(second) printed False for two books with the same title and year | Override Equals in the class, or use a record (see the FAQ) |
Overriding Equals but not GetHashCode | The build warned warning CS0659: 'Book' overrides Object.Equals(object o) but does not override Object.GetHashCode(). first.Equals(second) printed True, yet a HashSet<Book> built from both books counted 2 | Override GetHashCode with HashCode.Combine over the same values: the set then counted 1 |
Casting with Book book = (Book)obj!; inside Equals | first.Equals("Night Train") threw InvalidCastException: Unable to cast object of type 'System.String' to type 'Book'. | Use obj is Book book: the same call printed False |
Calling Equals on a variable that can be null | With Book? missing = null;, the build warned warning CS8602: Dereference of a possibly null reference. and missing.Equals(first) threw NullReferenceException: Object reference not set to an instance of an object. | Call the static object.Equals(missing, first), which checks both sides for null: it printed False |
FAQ
Can C# write Equals and GetHashCode for me?
Yes, a record does it. The equality guide: The compiler generates Equals, GetHashCode, and ==/!= members that compare every declared property value. With record Book(string Title, int Year); in place of the class, first.Equals(second) printed True, and so did first == second.
Why can the override compare the titles with ==?
Because string is a special case. The equality guide: Strings are classes, but == and Equals compare string content, not identity. So Title == book.Title compares the text of the two titles.
What does first.Equals(null) return?
False, with no exception, because a declaration pattern never matches null. The C# reference: A declaration pattern with type T matches an expression when an expression result is non-null and any of the following conditions are true, and the conditions it lists are about the type.
Conclusion
To compare objects of your own class by value, override Equals so that it compares the values that make two objects the same, with obj is Book book so that null and other types return false. Override GetHashCode with HashCode.Combine over the same values. == keeps comparing references on a class, and a record writes all of these members for you.
Additional Resources
- Object.Equals — the method you override, and the static
Equals(Object, Object). - Equality comparisons — value equality, reference equality and records.
- Equality operators — what
==compares, and equality in class hierarchies. - Declaration and type patterns — the
obj is Book bookcheck. - HashCode.Combine — one hash code from several values.
