The solution is simples!I have a problem where I need to compare two objects
If you know what type they are supposed to be you could also check for the generic IComparable<T> interface and potentially use that, but the non-generic one is probably your best bet.Code:object first = GetFirstObject (); object second = GetSecondObject (); if (first is IComparable) return ((IComparable) first).CompareTo (second) < 0;
If the objects don't support the IComparable interface the only way to use '>' or '<' to compare the items is to actually cast them in code to the correct type as follows:
Code:object first = GetFirstObject (); object second = GetSecondObject (); if (first is MyClass && second is MyClass) return (MyClass)first < (MyClass) second; else throw new Exception ("Cannot compare");




Reply With Quote
