Stefan Monov
Stefan Monov

Reputation: 11732

In a struct, is it valid to implement operator== via Equals, but not override Equals and GetHashCode?

Is this valid?

public struct MyStruct
{
    public int Foo { get; set; }

    public static bool operator ==(MyStruct a, MyStruct b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(MyStruct a, MyStruct b)
    {
        return !a.Equals(b);
    }
}

(I know it's slightly inefficient because Object.Equals uses reflection for value types by default. But is it valid?)

I'm asking because ReSharper highlights it and warns me that MyStruct defines operator '==' or operator '!=' but does not provide 'Object.Equals(object o)' and 'Object.GetHashCode()'.

Upvotes: 3

Views: 578

Answers (3)

HCL
HCL

Reputation: 36785

I think this may be interesting.

Upvotes: 4

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

It's valid, in terms of the fact that it compiles. But it's "invalid" in the sense that it breaks all expectations of users of your class - the framework design guidelines specify that you shouldn't implement functionality that only exists in operator overloads - that such methods should be accessible in other ways. And the standard is that Object.Equals and operator== implement the same functionality.

(Can only find the 1.1 version of the guidelines at the moment):

Provide alternate signatures. Most languages do not support operator overloading. For this reason, it is a CLS requirement for all types that overload operators to include a secondary method with an appropriate domain-specific name that provides the equivalent functionality. It is a Common Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant.

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128387

Valid? Yes. But it doesn't buy you anything.

Upvotes: 3

Related Questions