Gurg Hackpof
Gurg Hackpof

Reputation: 1344

Even if I know how/when to overload operator==, WHY should i do it?

Assuming I am designing a collection of objects for use by others and assuming I have read and understood (huh?) most threads about the differences between operator== and Equals(), WHY should I ever implement operator==?

Stealing an example from this thread, using it can be quite error prone:

object x = "hello";
object y = 'h' + "ello"; // ensure it's a different reference
(x == y); // evaluates to FALSE
string x = "hello";
string y = 'h' + "ello"; // ensure it's a different reference
(x == y); // evaluates to TRUE

So, can I tell my users to just use Equals() and ReferenceEquals() and that's it? What am I missing there?

Upvotes: 7

Views: 170

Answers (4)

s3rius
s3rius

Reputation: 1452

For me it's a question of what I generally want to do with the objects.

Take strings for example. In 99% of all cases you compare two strings to check for equality and not whether both variables point to the same string.

You also write:

int x, y;
if( x == y ) ..

So why would you want to force yourself to use:

BigNum x, y;
if( x.Equals(y) ) ...

Of course it's a source of errors (as most operator overloading is), but I think given the right context (e.g. an object where it's obvious you'd want to compare it's value) then it's a good thing to overload. If it's ambiguous then I'd always stick to Equals() and not overload ==.

Upvotes: 0

AakashM
AakashM

Reputation: 63378

WHY should I ever implement operator==?

For the convenience of the users of your type. If you are the only user, and you're happy to always test equality by invoking Equals, then you don't need to.

But if you were implementing, say, a complex number type1, I as a consumer of your type would be extremely disappointed to discover I couldn't do:

var z = new Complex(1, 0);
var c = new Complex(1, 0);
var eq = z == c;

but intead had to say

var eq = Complex.Equals(z, c);

1 I know there is one...

Upvotes: 0

Christian Hayter
Christian Hayter

Reputation: 31071

You implement == as a convenience for the users of your API. If you feel so strongly that users of your API would be confused by it, then don't implement it. Personally I would disagree with you, but it's your decision at the end of the day.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503934

You can tell your users just to use Equals... but I for one find it very handy that various types (including String) overload ==. Yes, you need to be aware of the way that overload resolution works, but for most experienced developers I suspect that isn't a problem most of the time, whereas:

if (Equals(x, y))

ends up looking nastier than

if (x == y)

in my view. Note that these are both different to

if (x.Equals(y))

which will blow up if x is null, of course...

If you prefer not to overload == then it's not like anything will fail - you just may get disgruntled users.

Upvotes: 8

Related Questions