IEquatable<T>. :
public class SubjectDTO: IEquatable<SubjectDTO>
{
public string Id;
public bool Equals(SubjectDTO other)
{
return Object.Equals(Id, other.Id);
}
public override int GetHashCode()
{
return Id == null ? 1 : Id.GetHashCode();
}
}
Looks fine, right? But when you try, you will find an amazing result:
var a = new SubjectDTO() { Id = "1"};
var b = new SubjectDTO() { Id = "1"};
Console.WriteLine(Object.Equals(a, b));
Console.WriteLine(a.Equals(b));
False
True
AND? Well, itβs important to overrideEquals(object other) :
public override bool Equals(object other)
{
return other == null ? false : Equals(other as SubjectDTO);
}
When you add it to the class SubjectDTO, it will work as expected.
source
share