Why do I get InvalidCastException when converting from double to decimal

I am trying to debug an application that receives an InvalidCastException. Fault line

decimal d = (decimal)row[denominator]; 

checking this in the debugger (see screenshot below), the line [denominator] has a double value, the value is 8.0, as far as I can tell. Awfully there shouldn't be any problems casting to decimal?

(The type "string" is from 3. party library , which is again populated with data from MySQL. The problem arose when testing on an older MySQL server, which, apparently, returns some aggregates like double vs decimal on MySQL 5.1 - the same query, exact copy of the data in the database)

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

Any help on how I could continue this study?

+7
c # exception
source share
8 answers

Eric Lippert spoke in detail about this in detail. At first I agree with this non-intuitively, but he explains well: Representation and identification

+10
source share

You need to first transfer it to double, since row[denominator] is a double box as an object that is.

 decimal d = (decimal)((double)row[denominator]); 
+6
source share

I would try

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

or

 decimal d = 0; if (!decimal.TryParse(row[denominator], out d)) //do something 
+4
source share

You can use:

 double d1 = (double)row[denominator]; decimal d = (decimal) d1; 

Or, of course, shorten this to:

 decimal d = (decimal) (double)(row[denominator]); 

Since there is an unboxing step, you need to follow 2 steps.

+3
source share

Suggestion: try using Convert.ToDecimal () instead of a direct cast.

+3
source share

Try throwing it on double . row[denominator] enclosed in a box, so direct decimal text will not work.

+2
source share

Judging by the error message and the description, I assume that the line [denominator] is a double box, so the type of object. Unboxing can only be done with the correct base data type, since the runtime is no longer where you can find the actual conversion operator from double to decimal (in your case, it tries to find the operator that converts the object to decimal, but that is the unboxing operator and the base type are not decimal.So the correct way should be to convert first to double and then to decimal:

 decimal d = (decimal)(double)row[denominator]; 
+2
source share

just

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

Thus, you do not need to worry about all the problems with casting.

0
source share

All Articles