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?
You can tell your users just to use
Equals… but I for one find it very handy that various types (includingString) 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:ends up looking nastier than
in my view. Note that these are both different to
which will blow up if
xis null, of course…If you prefer not to overload
==then it’s not like anything will fail – you just may get disgruntled users.