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...
Diego





