Overview
- Enables instances of a class to be compared for equality.
- e.g.
if (a.Equals(b))
- e.g.
Good practice
- Whenever implementing IEquatable, also override Object.Equals and if needed the == and != operators.
- See Implementing IEquatable Properly for more details.
Examples
Comparing Custom Class
class MyNumber : IEquatable<MyNumber>
{
private int _x;
public int X
{
get { return this._x; }
set { this._x = value; }
}
public MyNumber(int x)
{
this._x = x;
}
public override int GetHashCode()
{
return this._x.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (!(obj is MyNumber))
{
return false;
}
else
{
return Equals(obj as MyNumber);
}
}
#region IEquatable<MyNumber> Members
public bool Equals(MyNumber other)
{
if (other == null)
{
return false;
}
else
{
return (other.X == this.X);
}
}
#endregion
public static bool operator ==(MyNumber a, MyNumber b)
{
if (object.ReferenceEquals(a, b)) return true;
if (object.ReferenceEquals(a, null)) return false;
if (object.ReferenceEquals(b, null)) return false;
return a.Equals(b);
}
public static bool operator !=(MyNumber a, MyNumber b)
{
return !(a == b);
}
}
MyNumber a = new MyNumber(10);
MyNumber b = new MyNumber(10);
Console.WriteLine(a.Equals(b)); // True
Console.WriteLine(a == b); // True
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




