For example I have class
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
How to override GetHashCode in this class?
For example I have class
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
How to override GetHashCode in this class?
You should base your object's hashcode calculation on immutable fields, if you can make Person
's FirstName and LastName fields immutable, you can use the following pattern based on Josh Bloch's suggestion:
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + FirstName.GetHashCode();
hash = hash * 31 + LastName.GetHashCode();
return hash;
}
public override int GetHashCode()
{
return String.Concat(FirstName, LastName).GetHashCode();
}
You can do something like this:
public override int GetHashCode()
{
return FirstName.GetHashCode() ^ LastName.GetHashCode()
}
Check this for more