Mocco
Mocco

Reputation: 1223

Overloading operator == to check euqity of two objects

Yesterday I asked about using overloading operators and nobody mentioned that its quite common and often used to check equity of two objects like strings, colors..

Also in this case it is correct to overload == if my types represent some objects that could be checked for equity of their fields etc. Sure I do not mean checking whether the variables point to the same object.

Upvotes: 1

Views: 112

Answers (4)

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

In my opinion is better to use == to check for reference equality and use .Equals(Object obj) for custom equality.

That way you will have two ways of comparing instead of one.

Anyway take in mind that if you redefine Equality you should redefine the GetHashCode() too so two objects that are equal return the same hash code.

Upvotes: 1

Tom Quarendon
Tom Quarendon

Reputation: 5708

Not quite sure what your question is, in that you seem to have answered it yourself. You can overload operator== etc to check that two objects are the same, so in your examples of strings or colours, that two strings have the same actual contents, or that two colours have the same RGB values. As you say, this is distinct from two variables pointing at the same object. You might want to check out the MSDN section

Operator Overloading Tutorial

for more information on overloading.

Similar question with more information, including a list of the operators that you can overload: why C# not allow operator overloading?

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

Yes, it's reasonable to overload the == operator (and != at the same time, of course).

You need to be aware that it is overloading rather than overriding, so if you ever have:

object first = ...;
object second = ...;

if (first == second)

that will check for reference equality regardless of what you've done.

Upvotes: 2

Ikke
Ikke

Reputation: 101221

You can basically decide yourself what equity means. If it's to you that some fields are the same, then sure, check for that.

Upvotes: 1

Related Questions