PC Review


Reply
Thread Tools Rate Thread

Argument Exception with Double.CompareTo

 
 
Brian Richards
Guest
Posts: n/a
 
      12th Jun 2006
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


 
Reply With Quote
 
 
 
 
Jon Skeet [C# MVP]
Guest
Posts: n/a
 
      12th Jun 2006
Brian Richards <(E-Mail Removed)> wrote:
> 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).

--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
 
Reply With Quote
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Throwing Argument exception when method argument is a Guid Andy B Microsoft VB .NET 2 11th Jan 2009 06:38 PM
'System.ArithmeticException was unhandled' at System.Double.CompareTo(Double value) when comparing with Double.NaN vve Microsoft Dot NET Framework 0 14th May 2007 02:13 PM
double.Parse produces overflow exception on double.MinValue Samuel R. Neff Microsoft C# .NET 2 6th Mar 2007 06:36 PM
Argument Exception with Double.CompareTo (ignore previous) Brian Richards Microsoft C# .NET 0 12th Jun 2006 10:35 PM
Argument Exception with Double.CompareTo Brian Richards Microsoft C# .NET 0 12th Jun 2006 10:32 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 04:22 PM.