Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

  • Are there maybe pieces of the standard code base that use == and there is no way around it?

  • Is the == performance a lot better in some important cases? (well, ok, Equals is a virtual so it's gonna be a bit slower all the time, but i cannot see any use case where this actually becomes a bottleneck)

  • something else?
like image 856
Gurg Hackpof Avatar asked Jan 26 '12 10:01

Gurg Hackpof


1 Answers

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.

like image 182
Jon Skeet Avatar answered Nov 03 '22 00:11

Jon Skeet