implementing Equals but not GetHashCode in c#

Possible Duplicate:
Why is it important to override GetHashCode when Equals method is overriden in C#?

I dont implement the GetHashCode method of the Object class. so I get a number of warnings.

Is there a way to check for equality where I just check the hash code in the Equals method, so implement both Equals and GetHashCode and not get the "Object.GetHashCode not implemented warning?".

what will happen if i just implement the Equals and not implement the GetHashCode? instances of myclass are updatable in my application.

public class MyClass{

private string x;
private string y;

public override bool Equals(object obj)
        {

            try
            {

                 return    Object.Equals(this.x, obj.x)
                        && Object.Equals(this.y, obj.y);

            }
            catch(Exception Ex)
            {
                log.Debug(Ex.StackTrace);
                throw; 
            }
        }

}

If you implement Equals but not GetHashCode , then if your class is used in any data structure which uses hashing ( HashSet<T> , Dictionary<K,V> , etc.) it will behave incorrectly. Even if you don't explicitly use those data structures, it's possible that they're used by some code (ie, some Linq operations use HashSets), so it's safer to just override GetHashCode as well.


GetHashCode is used for storing and retrieving objects in a has table, ie, it is another way to judge object equality.

If you override one ( Equals ) and not the other ( GetHashCode ) then you run the risk of encountering inconsistent behavior when using GetHashCode (ie, plopping your objects in a collection implemented as a hash table) versus Equals() .

You may enjoy reading this post by Eric Lippert on the subject.


If you don't implement GetHashCode , your class will behave erratically when used as a key in structures like dictionaries or hash sets. If you want to use those types of structures, there's no way around it. Technically, your application will work if you stay away from those, but it's bad form, and anyone else who uses your classes will be in for a rude surprise.

链接地址: http://www.djcxy.com/p/39782.html

上一篇: C#重写GetHashCode的字符串类型

下一篇: 在c#中实现Equals但不是GetHashCode