Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I override == for object and MyType?

Tags:

c#

I have a struct called MyType that implements IEquatable<MyType>.

I have implemented operator ==(MyType x, MyType y), but should I also implement operator ==(MyType x, object y) for the case below?

For example:

public static bool operator ==(MyType x, object y)
{
    if (y is MyType)
    {
        return x == (MyType)y;
    }

    return false;
}

Usage:

var a = new MyType();
object b = new MyType();

var result = (a == b); // ?
like image 596
sdgfsdh Avatar asked Jan 30 '17 10:01

sdgfsdh


1 Answers

No CTS type does this, as far as I know. Good examples include Decimal and DateTime, which both only implement equality for their respective types and not for their base types or interfaces.

Moreover, this implementation may encourage comparing virtually any type with your struct, even other structs, and someone who might use your code in the future may think comparing MyType with MyOtherType could make sense, while all it would do is boxing the other type and then returning false. Also one usually interprets == on object as meaning reference equality.

In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

The documentation does not tell which equality operators you should overload, and the second sentence may actually be interpreted in the terms of MyType == object being consistent with MyType.Equals(object). However, the fact that no .NET types actually do this and that it leads to confusion are sufficient to say that it is not a good practice.

If other types can be treated as MyType, overload the explicit or implicit cast.

like image 79
IS4 Avatar answered Oct 09 '22 16:10

IS4