Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# System.Object Object.Equals

Koray Erkan
Koray Erkan
1,235 Points

Overriding Equals()

I didn't understand why we overrode System.Object's Equals() method. What is the wrong with the original one?

7 Answers

Because, even if the objects are the same on the surface, they may have a different location in memory. And if they have a different location in memory, they are not the same object, and are therefore, not equal.

For example, var obj1 = new Object, then var obj2 = obj1 leads to default equivalency because they point to the same object in memory.

But

var obj1 = new Object (first_name = "John", last_name = "Smith"); var obj2 = new Object (first_name = "John", last_name = "Smith");

creates two objects in memory, and they don't then match by default equals.

So we override equals to check for the conditions we want the program to use (such as first_name, last_name), rather than the conditions of memory-location.

[MOD: switched comment to answer]

No, you will not have to override equals for such things as primitive types (Boolean, int32, double, etc.), nor for strings. Those will work as expected.

Koray Erkan
Koray Erkan
1,235 Points

But this rule doesn't affect when dealing with / comparing numeric types, boolean, or strings right?

Koray Erkan
Koray Erkan
1,235 Points

Thank you Lukas. I understood the situation.

Maddalena Menolascina
Maddalena Menolascina
6,668 Points

I had the same doubt, Thank you Lukas

Jamie Wyton
Jamie Wyton
3,011 Points

So in your first example, var obj1 = new Object, then var obj2 = obj1. Because they point to the same object in memory, does that mean if I was to change one Id also be changing the other?

Yes, that is correct. You can verify this with a Console.WriteLine or by debugging your program.

cheers luckas