Argument Exception with Double.CompareTo

  • Thread starter Thread starter Brian Richards
  • Start date Start date
B

Brian Richards

This code throws an exception:

Double foo = 1.0;
Console.WriteLine(((IComparable)foo).CompareTo(1));

But this does not:

Double foo = 1.0;
Console.WriteLine(foo.CompareTo(1));


Does anyone know why? I'm assuming it has to do with the way Double
implements IComparable and it's trying to call CompareTo(double) and not
CompareTo(object) when cast as IComparable. Given that can anyone think of a
workaround for doing something like.

object foo = 1.0;
object bar = 2;

if (foo is IComparable)
{
return ((IComparable)foo).CompareTo(bar);//throws exception
}
else
{
...
}

Thanks

Brian
 
Brian Richards said:
This code throws an exception:

Double foo = 1.0;
Console.WriteLine(((IComparable)foo).CompareTo(1));

But this does not:

Double foo = 1.0;
Console.WriteLine(foo.CompareTo(1));


Does anyone know why? I'm assuming it has to do with the way Double
implements IComparable and it's trying to call CompareTo(double) and not
CompareTo(object) when cast as IComparable.

No, when it's cast to IComparable, it's calling CompareTo(object),
whereas when it's not cast, the integer is being implicitly converted
to a double before calling CompareTo(double).
 
Back
Top