I wrote some code which compares numbers of all datatypes with each other. The standard Comparer which is implemented by every number Type only compares numbers of the same type.
I cast to decimal because this is the largest possible number type and should cover everything.
What do you think about the code? Room for improvement? How to handle NaN the best way? Do you think BigInt and Real numbers should be a part of it?
internal class UniversalNumberComparer : IComparer
{
public int Compare(object x, object y)
{
if(!IsNumber(x) || !IsNumber(y))
throw new InvalidOperationException();
return x == null
? (y == null ? 0 : -1)
: (y == null ? 1 : Decimal.Compare(Convert.ToDecimal(x), Convert.ToDecimal(y)));
}
private static readonly TypeCode[] _TypeCode ={TypeCode.Byte,
TypeCode.Decimal,
TypeCode.Double,
TypeCode.Int16,
TypeCode.Int32,
TypeCode.Int64,
TypeCode.SByte,
TypeCode.Single,
TypeCode.UInt16,
TypeCode.UInt32,
TypeCode.UInt64};
private bool IsNumber(object value)
{
return (value == null) || (Array.IndexOf(_TypeCode, Type.GetTypeCode(value.GetType())) != -1);
}
}
Update:
Based on your Feedback i refined the UniversalNumberComparer.
decimal. Also, what aboutBigInteger? – svick Mar 4 at 16:03