Course contentsShow
← C#
Lesson 78 of 1,9081. C# Language FoundationsFree lesson

Value-Based Equality vs Reference Equality

Select appropriate equality strategies to ensure logical correctness.

In this lesson, you will learn how to distinguish between checking if two variables point to the exact same spot in memory versus checking if they contain the same data.

Reference Equality (The "Address" Check)

In C#, reference types (like class) are stored as references—pointers to a location in memory. When you use the == operator on two objects, C# defaults to Reference Equality. This asks: "Do these two variables point to the exact same instance in the heap?"

var person1 = new Person { Name = "Alice" };
var person2 = new Person { Name = "Alice" };

bool areSameReference = (person1 == person2); // False

Even though both people share the same name, they are two distinct objects in memory. The computer sees them as different.

Value-Based Equality (The "Content" Check)

Value-Based Equality asks: "Do these two objects hold the same data?" For value types (like struct), C# performs a bit-by-bit comparison of the contents.

However, for reference types, we often want to treat objects as "equal" if their properties match. To achieve this, we must define logic (usually by overriding methods) to compare the state of the objects rather than their memory addresses. If you have two separate struct instances with the same values, C# treats them as equal automatically because they are compared by their contents, not their memory address.

Why it Matters

Choosing the right strategy is vital for logical correctness. If you are building a system that tracks unique identities (like database records), you want Reference Equality to ensure you are modifying the exact same object. If you are building a system that compares values (like coordinates or calculated results), you want Value-Based Equality to ensure that (10, 20) is considered the same as another (10, 20), regardless of where they sit in memory.

When you fail to distinguish these, you might end up with bugs where two "equal" objects are treated as different, or vice versa, leading to unexpected behavior in your collections and logic.

Key Takeaway: Reference equality checks if two variables point to the same memory address, while value-based equality checks if two variables contain the same data; choosing the wrong one will lead to logical errors in your program.