In the structure, is it permissible to implement the == operator through Equals, but not override Equals and GetHashCode?

It's really?

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 this is a little inefficient because Object.Equals uses reflection for default types. But is it really?)

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

+3
source share
3 answers

Really? Yes. But he doesn’t buy anything.

+3
source

I think this one might be interesting.

+4
source

, , . "" , - , , , - . , Object.Equals operator == .

( 1.1 ):

Provide alternative 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 name that provides equivalent functionality. This is the General Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant.

+2
source

Source: https://habr.com/ru/post/1763405/


All Articles