Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Overload == Operator?

How does the == operator really function in C#? If it used to compare objects of class A, will it try to match all of A's properties, or will it look for pointers to the same memory location (or maybe something else)?

Let's create a hypothetical example. I'm writing an application that utilizes the Twitter API, and it has a Tweet class, which has all the properties of a single tweet: text, sender, date&time, source, etc. If I want to compare objects of class Tweet for equivalence, can I just use:

Tweet a, b;
if (a == b)
{
//do something...
}

Will that check for equivalence of all the properties of the Tweet class between a and b?

If not, would the correct approach be to overload the == operator to explicitly check for equivalence of all the fields?

UPDATE: From the first two answers, am I right in assuming:

  • If the == operator or Equals method is not overloaded for a class, the == operator for the object class is used.
  • The == operator for the object class checks for equality in memory location.
  • I have to overload the == operator or the Equals method to accomplish this task.
  • In the overload, I have to check for equivalence in properties manually, so there is no way to do it semi-automatically, say, in a loop, right?

UPDATE #2: Yuriy made a comment that it is possible to do check for equivalence in properties in the == operator with reflection. How can this be done? Could you give me some sample code? Thanks!

like image 628
Maxim Zaslavsky Avatar asked Jan 01 '26 18:01

Maxim Zaslavsky


1 Answers

For reference types, the default implementations of both the == operator and the Equals() method will simply check that both objects have the same reference, and are therefore the same instance.

If you want to check the contents of two different objects are equal then you must write the code to do it yourself, one way or another. It would be possible to do with reflection (the MbUnit test framework does something along these lines) but with a heavy performance penalty and a good chance that it wouldn't do quite what you expected anyway, and you should implement == or Equals and GetHashCode by hand.

like image 153
GraemeF Avatar answered Jan 03 '26 10:01

GraemeF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!