Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing Equals but not GetHashCode in c# [duplicate]

Tags:

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; 
            }
        }

}

2 Answers

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 (i.e., some Linq operations use HashSets), so it's safer to just override GetHashCode as well.

like image 156
carlosfigueira Avatar answered Jan 03 '26 11:01

carlosfigueira


GetHashCode is used for storing and retrieving objects in a has table, i.e., 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 (i.e., 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.

like image 36
Ed S. Avatar answered Jan 03 '26 12:01

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!