Reference to the equality operator in the implementation of the equality operator

Using Reflector or DotPeek, System.Linq.Data.Binary, the implementation of overloading the equality operator is as follows:

[Serializable, DataContract] public sealed class Binary : IEquatable<Binary> { ... public static bool operator ==(Binary binary1, Binary binary2) { return ((binary1 == binary2) || (((binary1 == null) && (binary2 == null)) || (((binary1 != null) && (binary2 != null)) && binary1.EqualsTo(binary2)))); } 

Do I need to miss something obvious or is there a mechanism from which I do not know (for example, an implicitly calling object == inside the body?). I admit that I rarely have to overload standard operators.

Why doesn't this implementation lead to infinite recursion (that a simple test shows that it doesn't solve endlessly)? The first conditional expression is binary1 == binary2 in the framework of the operator overload implementation, which will be called if you used binary_1 binary2 outside the implementation, and I would also think inside.

+5
c #
source share
2 answers

I expect this to be a bug in your decompiler. Reddate Reflector has / has the same error, and I found it in ILSpy .

The reason this is difficult to decompile is because it subtly tests C # overload rules. The original code most likely looked like (object)obj1==(object)obj2 , but this conversion cannot be seen in the IL itself. Casting any reference type to a base type is non-op with respect to runtime. However, it gets C # to select reference reference opcodes instead of calling overloaded equality operators.

IMO the right way to implement this in a decompiler is to always decompile reference equality checks on (object)obj1==(object)obj2 , and then optimize redundant casts if they do not affect overload resolution. This approach will also eliminate similar problems with method overloading.

+5
source share

This is obviously a bug in your version of ReSharper (and dotpeek). Version 6.0 (6.0.2202.688) ReSharper does this correctly:

  public static bool operator ==(Binary binary1, Binary binary2) { if ((object)binary1 == (object)binary2) return true; if ((object)binary1 == null && (object)binary2 == null) return true; if ((object)binary1 == null || (object)binary2 == null) return false; return binary1.EqualsTo(binary2); } 
+2
source share

All Articles