Override Equals and GetHashCode on custom C# with Example



Override Equals and GetHashCode on custom C# with Example

types 
For a class Person like: 
public class Person 
{ 
public string Name { get; set; } 
public int Age { get; set; } 
public string Clothes { get; set; } 
} 
var person1 = new Person { Name = "Jon", Age = 20, Clothes = "some clothes" }; 
var person2 = new Person { Name = "Jon", Age = 20, Clothes = "some other clothes" }; 
bool result = person1.Equals(person2); //false because it's reference Equals 
But defining Equals and GetHashCode as follows: 
public class Person 
{ 
public string Name { get; set; } 
 

public int Age { get; set; } 
public string Clothes { get; set; } 
public override bool Equals(object obj) 
{ 
var person = obj as Person; 
if(person == null) return false; 
return Name == person.Name && Age == person.Age; //the clothes are not important when 
comparing two persons 
} 
public override int GetHashCode() 
{ 
return Name.GetHashCode()*Age; 
} 
} 
var person1 = new Person { Name = "Jon", Age = 20, Clothes = "some clothes" }; 
var person2 = new Person { Name = "Jon", Age = 20, Clothes = "some other clothes" }; 
bool result = person1.Equals(person2); // result is true 
Also using LINQ to make different queries on persons will check both Equals and GetHashCode: 
var persons = new List 
{ 
new Person{ Name = "Jon", Age = 20, Clothes = "some clothes"}, 
new Person{ Name = "Dave", Age = 20, Clothes = "some other clothes"}, 
new Person{ Name = "Jon", Age = 20, Clothes = ""} 
}; 
var distinctPersons = persons.Distinct().ToList();//distinctPersons  has  Count  =  2 

0 Comment's

Comment Form

Submit Comment