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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With