Implementing equality of derived reference types by overriding the == operator with C# .NET
May 20, 2015 1 Comment
In this post we saw one solution to override the == operator for a reference type to implement equality checking. Here’s a reminder of the Person class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public static bool operator ==(Person personOne, Person personTwo)
{
return personOne.Id == personTwo.Id;
}
public static bool operator !=(Person personOne, Person personTwo)
{
return personOne.Id != personTwo.Id;
}
public override int GetHashCode()
{
return Id;
}
}