0

In my custom sorting algorithm, I need to compare numeric types stored as Objects in an array. We can have SByte, Double, Int32, etc values mixed in one array. How can I compare two values of that array in my IComparer implementation?


An example. Let's say we have two numeric values:

object var1 = (sbyte)-8;
object var2 = (double)123.456;

It would be nice if code like the following one worked, but it fails:

IComparable cmp1 = var1 as IComparable;
IComparable cmp2 = var2 as IComparable;
MessageBox.Show(cmp1.CompareTo(cmp2).ToString());

How can I compare two boxed numeric values in .NET 2.0?

TecMan
  • 2,743
  • 2
  • 30
  • 64
  • Unfortunately you must convert them to a common type inspecting boxed value type. There isn't much you can do for that. If you're limited to primitive types you have to write some boilerplate code (byte, sbyte, int, uint, float and other may all be converted to double for comparison, for example) but it's viable. – Adriano Repetti Mar 11 '15 at 12:39
  • @AdrianoRepetti, can I convert my object values to a "wide" type like Double or Decimal and then compare them? Or did you mean something else? – TecMan Mar 11 '15 at 12:49
  • Yes you can but you can't do `(double)var1`. First you have to unbox `(double)(sbyte)var1` or use `Convert.ToDouble(var1)`. Of course to decide if you need to convert to `double` or `long` or `decimal` or `string` you need to inspect type and then convert to a wider one (if you don't want to handle each combination separately). – Adriano Repetti Mar 11 '15 at 12:54
  • @AdrianoRepetti, I think I can convert any numeric type to double and then simply compare to double's. A double value can store any integer data type without precision loss; the same is true for single's. As for decimal values, I think we can neglect possible precision loss in our context. – TecMan Mar 11 '15 at 14:12
  • 1
    Not whole `Int64`/`UInt64` can be _safely_ converted to `double`! For example `(long)(double)longValue != longValue` when `longValue = 9223372036854775807`. In general there is a _maximum safe integer that can be represented in floating point_ without precision loss. It's not only about integers: there are also conversion you can't do from `double` to/from `decimal` (and if you're using `decimal` then there is a reason...to ignore it may be harmful). Then include on this also non primitive types (such as `Complex` and `BigInteger`). – Adriano Repetti Mar 11 '15 at 14:50
  • @AdrianoRepetti, so what do you suggest? How can I compare two numeric values of unknown types? If possible, write your code/pseudocode as an answer. – TecMan Mar 11 '15 at 16:03
  • Problem is that you can't do it in a reliable way unless you set some "fixed points". For example: I won't use decimal, I don't need to compare double with integer...and so on – Adriano Repetti Mar 11 '15 at 16:53

0 Answers0