简体   繁体   中英

C# operator overloading == and pragma warnings 660 & 661 not overriding Equals and GetHashCode when irrelevant

Why does the C# compiler complain with pragma warning 660 & 661

  • "FooClass" defines operator == or operator != but does not override Object.Equals(object o)
  • "FooClass" defines operator == or operator != but does not override Object.GetHashCode()

When adding additional operators, such as:

public static bool operator ==(FooClass foo, string fooId)

I am not specifying

public static bool operator ==(FooClass foo, FooClass foo2)

Which this would make sense to override Object.Equals and GetHashCode.

Is this just a limitation in the compiler that it's not properly checking the arguments specified in the operator?

The general guideline is doing foo == bar should return the same result as foo.Equals(bar) , that is the reason for the warning. It is a guideline, not a requirement, and that is why it is a warning instead of a error.

The 2nd warning is because of the rule that if(foo.Equals(bar)) foo.GetHashCode() == bar.GetHashCode() . If two objects are equal, their hash codes should also be equal. Many things in the .NET framework and 3rd party libraries rely on this so if you don't do it things like Dictionary that use GetHashCode() for lookups is going to break.

So if I can do

FooClass foo = new FooClass("Foo");
if(foo == "Foo")
{
   //...
}

I expect to be able to do

FooClass foo = new FooClass("Foo");
Hashtable hash = new Hashtable();
hash.Add(foo, "Bar");
var result = hash["Foo"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM