Possible Duplicate:
Why is it important to override GetHashCode when Equals method is overriden in C#?
I was looking into the following class in my Object Model
and could not understand the significance of adding GetHashCode()
in the Class
.
Sample Class
public class SampleClass
{
public int ID { get; set; }
public String Name { get; set; }
public String SSN_Number { get; set; }
public override bool Equals(Object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
SampleClass cls = (SampleClass)obj;
return (ID == cls.ID) &&
(Name == cls.Name) &&
(SSN_Number == cls.SSN_Number);
}
public override int GetHashCode()
{
return ID.GetHashCode() ^ Name.GetHashCode() ^ SSN_Number.GetHashCode();
}
}
Suppose I have a list of Sample Class
Object and I want to get a specific index. Then Equals()
can help me to get that record. Why should I use GetHashCode()
?