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 trialKoray Erkan
1,235 PointsOverriding Equals()
I didn't understand why we overrode System.Object's Equals() method. What is the wrong with the original one?
7 Answers
Lukas Dahlberg
53,736 PointsBecause, 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]
Lukas Dahlberg
53,736 PointsNo, 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
1,235 PointsBut this rule doesn't affect when dealing with / comparing numeric types, boolean, or strings right?
Koray Erkan
1,235 PointsThank you Lukas. I understood the situation.
Maddalena Menolascina
6,668 PointsI had the same doubt, Thank you Lukas
Jamie Wyton
3,011 PointsSo 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?
Lukas Dahlberg
53,736 PointsYes, that is correct. You can verify this with a Console.WriteLine or by debugging your program.
chanjong kim
2,315 Pointscheers luckas