Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get InvalidCastException when casting a double to decimal

Tags:

c#

.net

exception

I'm trying to debug an application which gets an InvalidCastException. The failing line is

decimal d = (decimal)row[denominator];

inspecting this in the debugger(see screenshot below), row[denominator] holds a double with value 8.0 as far as I can tell. Surly there shouldn't be any problem casting that to a decimal ?

(The 'row' type is from 3. party library, which again is filled from data from MySQL. The issue arised when testing against an older MySQL server which apparently returns some aggregates as double vs decimal on MySQL 5.1 - same query ,exact same copy of data in the database)

Visual Studio Screenshot http://img18.imageshack.us/img18/3897/invaldicast.png

Any help on how I could further investigate this ?

like image 877
Anonym Avatar asked Nov 03 '09 12:11

Anonym


4 Answers

Eric Lippert has blogged about exactly this in depth. I agree it's unintuitive at first, but he explains it well: Representation and Identity

like image 89
SoftMemes Avatar answered Sep 22 '22 01:09

SoftMemes


You need to cast it to a double first as row[denominator] is a double boxed as an object i.e.

decimal d = (decimal)((double)row[denominator]);
like image 23
JDunkerley Avatar answered Sep 23 '22 01:09

JDunkerley


A suggestion: try using Convert.ToDecimal() instead of direct casting.

like image 4
Audrius Avatar answered Sep 25 '22 01:09

Audrius


I'd try

decimal d = Convert.ToDecimal(row[denominator]);

or

decimal d = 0;
if (!decimal.TryParse(row[denominator], out d))
    //do something
like image 4
Viktor Jevdokimov Avatar answered Sep 24 '22 01:09

Viktor Jevdokimov