Quantcast
Channel: Why is it important to override GetHashCode when Equals method is overridden? - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Why is it important to override GetHashCode when Equals method is overridden?

$
0
0

Given the following class

public class Foo{    public int FooId { get; set; }    public string FooName { get; set; }    public override bool Equals(object obj)    {        Foo fooItem = obj as Foo;        if (fooItem == null)         {           return false;        }        return fooItem.FooId == this.FooId;    }    public override int GetHashCode()    {        // Which is preferred?        return base.GetHashCode();        //return this.FooId.GetHashCode();    }}

I have overridden the Equals method because Foo represent a row for the Foos table. Which is the preferred method for overriding the GetHashCode?

Why is it important to override GetHashCode?


Viewing all articles
Browse latest Browse all 17

Latest Images

Trending Articles





Latest Images