Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

C#, cast to decimal fails

The following line is suddenly throwing an invalid cast after applying an Oracle patchset to take us from Oracle 9.2.01 to 9.2.0.5:

decimal val = (decimal) cmd.ExecuteScalar();

cmd is an OleDbCommand.

A "Quick Watch" of cmd.ExecuteScalar() shows:

-    cmd.ExecuteScalar()    {4608236.0}    System.Double
+    System.ValueType    {System.Double}    System.ValueType
    MinValue    -1.7976931348623157E+308    double
    MaxValue    1.7976931348623157E+308    double
    Epsilon    4.94065645841247E-324    double
    NegativeInfinity    NaN    double
    PositiveInfinity    NaN    double
    NaN    NaN    double
    m_value    4608237.0    double

Why would this be failing? 

AMS
Wednesday, September 22, 2004

Oracle's OLEDB driver may have changed from the release you were originally using.  You need to cast to double instead of decimal.


Thursday, September 23, 2004

Sorry...to clarify:

decimal val = (decimal) cmd.ExecuteScalar();

...should be...

double val = (double) cmd.ExecuteScalar();

or

Double val = Convert.ToDouble(cmd.ExecuteScalar());

Check the release documentation for the Oracle patch and you might find something about them changing types.


Thursday, September 23, 2004

But from what I've read, an explicit cast of a double to a decimal is valid.

I did solve it along the lines of the suggestion above, but still do not understand why it was a problem.

AMS
Thursday, September 23, 2004

ExecuteScalar returns an object.

The problem you're running into is that casting and conversion are done with the same set of code. For instance, this:

double d = 12.7;
decimal m = (decimal) d;

But what that's doing is a CONVERSION, not a CAST.

Now, if you do this:

double d= 12.7;
object o = d;
decimal m = (decimal) o;

It fails. Why? Because o is an object. The last line of code is a cast. When the object attempts to unbox a decimal, it sees that it really has a double in there, you have a type mismatch, and an error is thrown.

So, I think that Convert.ToDecimal() is really your friend here. Using the syntax that mixes casts and conversions is what's causing you to be tripped up.

Brad Wilson (dotnetguy.techieswithcats.com)
Sunday, September 26, 2004

Isn't Convert.*( ) like really slow though? I have made a practice of avoiding it at all costs.

Aaron
Sunday, September 26, 2004

*  Recent Topics

*  Fog Creek Home