casting ExecuteScalar() result c#

The problem here is that ExecuteScalar is returning an int which is boxed into an object. In order to convert to a double you must first unbox to an int then convert to a double

double collectionCharge = (double)(int)cmdCheck.ExecuteScalar();

Use the Convert.ToXXX to avoid invalid cast exceptions.

I.E

collectionCharge=Convert.ToDouble(cmdCheck.ExecuteScalar());

As it appears that ExecuteScalar returns an Object so the code:

double collectionCharge = (double)cmdCheck.ExecuteScalar();

Could still fail


With thanks to @DJKRAZE.

I updated my query to SELECT CASE(FREIGHT_PRICE AS FLOAT) which now works with the (double) cast.

double collectionCharge = (double)cmdCheck.ExecuteScalar();