posted on Friday, January 09, 2004 12:28 AM
by
taylorza
Boilerplate Code - Equality
Coming from a C/C++ background I have found it beneficial to build a library of coding patterns. These patterns help provide robust implementations of seemingly simple concepts that are plagued by complexities of either the language or environment.
I want to present some of the patterns that I use and hopefully verify there correctness through this medium. The first of these patterns is the overloading of the equality operator. The goal of this pattern is to provide a robust template that is implemented with the least amount of code an is easily plugged into any class requiring an overload of the equality operator.
The only methods to implement in this pattern are GetHashCode() and InternalCompare(), InternalCompare is the method used to perform the physical comparison of the objects. And to replace BoilerPlateClass with the name of the class.
public static bool operator ==(BoilerPlateClass obj1, BoilerPlateClass obj2)
{
// This will check for nulls and call your overloaded Equals to perform the comparison
return object.Equals(obj1,obj2);
}
public static bool operator !=(BoilerPlateClass obj1, BoilerPlateClass obj2)
{
return !(obj1 == obj2);
}
public override bool Equals(object obj)
{
// Short-circuit the comparison for obvious non-equality
if (obj == null || this.GetType() != obj.GetType())
{
return false;
}
if ( Object.ReferenceEquals( this,obj ) )
{
return true;
}
return InternalCompare( (BoilerPlateClass)obj );
}
public override int GetHashCode()
{
// Return hashcode for the instance
}
private bool InternalCompare( BoilerPlateClass obj )
{
// return result of comparison
}
Update :
Included suggestion by Kazuhiko Kikuchi to short-circuit overriden Equals method.