+ 2
C# - Not Equal?
Let's say you have a class called Score and overload the "+" operator to add two parameters . If you create objects of a class, set one equal to the others and then compare them, apparently they are not equal. Why is this? Score tm1 = new Score(2, 3); Score tm2 = new Score(4, 2); Score finalScores = tm1 + tm2; if (finalScores == (tm1+tm2)) {/*execute something*/} //this code does not execute if (finalScores != (tm1+tm2)) {/*execute something*/} //this code does execute
1 Answer
+ 4
You might ask yourself: "How is the C# compiler supposed to know when two complex object types are equal?"
If you think about it for a minute, you might come to the conclusion that you have to tell the compiler explicitly what "equality" means for your type. And thus conclude that you probably have to overload the comparison operators == and !=.
Returning to your code. As a language designer, what can you say about generic equality of two objects of any arbitrary type, even types that are not even invented yet? Not much except that two objects that are identical, that is two variables reference the same object in memory, must also be semantically equal. And that is what the generic == does. It looks to see if the objects referenced are identical, not semantically the same. And in your case 'finalScores' and the newly computed t1+t2 are two different objects at two different locations in memory. Hence they are not identical, thus possibly not equal.