Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()'.

like image 854
Stefan Monov Avatar asked Dec 06 '25 09:12

Stefan Monov


1 Answers

I think this may be interesting.

like image 135
HCL Avatar answered Dec 08 '25 21:12

HCL