Monday, June 28, 2010

Compare two object's values

Recently we encounter an event that receives two objects and we wanted to compare their values (before and after of a column 'changing' event on a datatable). Using '==' doesn't do the work because the implementation of '==' in object compares the actual reference and not the values.

This simple method does the work.

static bool CompareObjectsValues(object a, object b)
if (a.GetType()!=b.GetType() 
|| !(a is IComparable) || !(b is IComparable))
return false;

IComparable valA = a as IComparable;
IComparable valB = b as IComparable;

return (valA.CompareTo(valB) == 0);


Full sample to show the problem and test:
static bool Compare(object a, object b)
return (a == b);

static void Main(string[] args)
object a = new object();
object b = new object();

DateTime d1 = new DateTime(2010, 6, 27);
DateTime d2 = new DateTime(2010, 6, 27);

a = d1;
b = d2;

object c = a;

//returns 'true' -> same reference
Console.WriteLine(Compare(a , c)); 
//returns 'false'-> same value but not same reference -> problem
Console.WriteLine(Compare(a , b)); 
//returns 'true' -> compares values and not references
Console.WriteLine(CompareObjectsValues(a, b));


That's it...

1 comment: