开发者

Why do I get InvalidCastException when casting a double to decimal

开发者 https://www.devze.com 2022-12-09 22:52 出处:网络
I\'m trying to debug an application which gets an InvalidCastException. The failing line is decimal d = (decimal)row[denominator];

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 wi开发者_运维技巧th 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 ?


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


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]);


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


I'd try

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

or

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


row[denominator] is of type object. It contains a 'boxed' double. You can only convert boxed values back to their original type. And then do the normal conversions.

You can use:

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

Or, of course, shorten that to:

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

Because there is an unboxing step involved, you need 2 steps.


Try casting it to a double first. The row[denominator] is boxed, so a straight cast to decimal won't work.


Judging from the error message and description I assume that row[denominator] is a boxed double, so of type object. Unboxing can only be done to the correct underlying datattype, since the runtime doesn't now where to find the actual conversion operator from double to decimal (in your case it tries to find an operator which converts object to decimal, but that one is an unboxing operator and the underlying type is not decimal. So the right way should be to convert first to double and then to decimal:

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


just do

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

this way, you don't need to worry about all the casting problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消