Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# different MSDN guidelines about Equals implementation [closed]

Tags:

c#

msdn

Why do the following documents talk about different approaches when implementing Equals method?

  • [MSDN] Guidelines for Overriding Equals() and Operator == (C# Programming Guide)
  • [MSDN] Implementing the Equals Method

The second document (which is more recent) does not explicitly implement the strongly-typed version of Equals (like public bool Equals(MySuperTrooperClass o)).

What's underlying reason to drop the strongly-typed method from one of the guidelines and which approach should I use in my production code?

like image 855
Yippie-Ki-Yay Avatar asked Jul 12 '26 23:07

Yippie-Ki-Yay


2 Answers

There is no benefit to dropping the strongly-typed version. Quite the contrary, as the first page itself mentions

It is also recommended that in addition to implementing Equals (object), any class also implement Equals (type) for their own type, to enhance performance.

This is doubly true for value types.

I assume that the second page does not concern itself with this at all because only the weakly typed version is defined on System.Object. The strongly typed version typically goes hand in hand with implementing IEquatable<T>, the documentation for which mentions the interaction between Equals(T) and Equals(object).

like image 89
Jon Avatar answered Jul 15 '26 13:07

Jon


An unfortunate side-effect of Microsoft's decision to overload Equals in many primitive types is that there are many cases where even though ((Object)X).Equals(Y) will behave as an equivalence relation (which it should), because of implicit conversions, X.Equals(Y) will not. For example, 3.Equals(3.0) will return false, but (3.0).Equals(3) will return true. While the == operator isn't quite as bad (generally if X==Y, Y==X) it still doesn't specify an equivalence relation (e.g. if X = Int64.MaxValue, Y=X-1, and Z=(Double)X, then X==Z and Y==Z but X!=Y).

Perhaps the reason that Microsoft dropped the advice about providing an overload of Equals() which behaves identically to Equals(Object) is that while implicit casts may render the former incapable of behaving as an equivalence relation, the latter should behave as an equivalence relation, with no exceptions.

like image 44
supercat Avatar answered Jul 15 '26 12:07

supercat