IEquatable Interface
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- Enables instances of a class to be compared for equality.
- e.g.: if (a = = b)
Good practice
- Whenever implementing IEquatable, also override Object.Equals and if needed the == and != operator.
- 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 base.Equals(obj);
if (!(obj is MyNumber))
{
throw new InvalidCastException("The 'obj' argument is not a MyNumber object.");
}
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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



