husayt
husayt

Reputation: 15139

Math.Sign with Object parameter

What is the best (fastest) way to determine a sign of a numeric value passed in as Object? Just to make it clear, the value might be an int, double, Decimal or anything else comparable to 0. So we need Math.Sign analogue with object parameter in.

The solution needs to take into account boxing/unboxing concerns as well.

Upvotes: 1

Views: 83

Answers (3)

Dan Byström
Dan Byström

Reputation: 9244

or anything else comparable to 0

Then cast it to IComparable.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062745

how about

bool isNeg = ((dynamic)value) < 0;

?

I haven't tested it for all types, but looks feasible.

Update: seems to work for most:

static void Main()
{
    ShowNeg(byte.MinValue); ShowNeg(byte.MaxValue);
    ShowNeg(ushort.MinValue); ShowNeg(ushort.MaxValue);
    ShowNeg(uint.MinValue); ShowNeg(uint.MaxValue);
    ShowNeg(ulong.MinValue); ShowNeg(ulong.MaxValue);
    ShowNeg(sbyte.MinValue); ShowNeg(sbyte.MaxValue);
    ShowNeg(short.MinValue); ShowNeg(short.MaxValue);
    ShowNeg(int.MinValue); ShowNeg(int.MaxValue);
    ShowNeg(long.MinValue); ShowNeg(long.MaxValue);
    ShowNeg(float.MinValue); ShowNeg(float.MaxValue);
    ShowNeg(double.MinValue); ShowNeg(double.MaxValue);
    ShowNeg(decimal.MinValue); ShowNeg(decimal.MaxValue);
}
static void ShowNeg(object value)
{
    bool isNeg = ((dynamic)value) < 0;
    Console.WriteLine(isNeg);
}

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

The solution needs to take into account boxing/unboxing concerns as well.

What does this mean? Since you get an Object anyway, unboxing always happens.

The simplest solution is to convert the object to double and get the sign:

double d = Convert.ToDouble(obj);
return Math.Sign(d);

However, I would seriously question the design of your software if there are situations where an arbitrary number type gets boxed and passed to a function. This shouldn’t normally happen.

Upvotes: 2

Related Questions