C# Compare two object values
.net, c#
Solution
Thanks for your answers, the correct way was to check if the object implements IComparable and if it does - make a typecast and call CompareTo
if (valueX is IComparable)
{
var compareResult = ((IComparable)valueX).CompareTo((IComparable)valueY);
}
Problem
I currently have two objects (of the same type) that may represent any primitive value such as string, int, datetime etc. ``` var valueX = ...; var valueY = ...; ``` Atm I compare them on string level like this ``` var result = string.Compare(fieldValueX.ToString(), fieldValueY.ToString(), StringComparison.Ordinal); ``` But I need to compare them on type level (as ints if those happen to be ints ``` int i = 0; int j = 2; i.CompareTo(j); ``` , as dates if they happen to be date etc), something like ``` object.Compare(x,y); ``` That returns -1,0,1 in the same way. What are the ways to achieve that ?