casting ExecuteScalar() result c#

Stuart picture Stuart · Mar 15, 2013 · Viewed 18.5k times · Source

why would this work

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

but this produces an exception

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

System.InvalidCastException: Specified cast is not valid.

why would it not be valid?

EDIT I am trying to simply return a single result from a query, that gets the price of some freight. So I can't turn this into an int because it must have decimals, hence trying to cast to a double. I am still learning asp.net so if there's a better way to achieve this, please do point me in the right direction :)

EDIT 2 the full code with SQL...

using (SqlCommand cmdCheck = new SqlCommand("SELECT FREIGHT_PRICE FROM FREIGHT_QUOTER_BELNL_NEW WHERE CUSTOMER_NO = @CUSTOMER_NO AND COUNTRY = @COUNTRY AND ROUND(WEIGHT_FROM,0) < @WEIGHT AND ROUND(WEIGHT_TO,0) >= @WEIGHT AND SHIPVIA = '48';", connection))
                {
                    double collectionCharge = (double)cmdCheck.ExecuteScalar();
                    FreightAmount = collectionCharge;
                }

Answer

JaredPar picture JaredPar · Mar 15, 2013

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