Cast int to float

  • Thread starter Thread starter John Baro
  • Start date Start date
J

John Baro

I have a query that returns an Int32 that I execute with
Command.ExecuteScalar

when I try (float)Command.ExecuteScalar
it throws a
Specified cast is not valid
exception.
When I try (float)(int)Command.ExecuteScalar
it works.
Why?

TIA
JB
 
John said:
When I try (float)(int)Command.ExecuteScalar
it works.
Why?

ExecuteScalar does NOT return an "Int32". It returns an object!
So first you need to cast to the correct type. Then you can change it.
when I try (float)Command.ExecuteScalar
it throws a
Specified cast is not valid
exception.

Yes, because the return type is int and not float.

--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp
 
John Baro said:
I have a query that returns an Int32 that I execute with
Command.ExecuteScalar

when I try (float)Command.ExecuteScalar
it throws a
Specified cast is not valid
exception.
When I try (float)(int)Command.ExecuteScalar
it works.
Why?

When you unbox a boxed value type, you have to give the exact correct
type - int in this case. You can then go through explicit conversion of
the int to the float. You just can't unbox an int directly to a float.
 
The object returned is a boxed int. A boxed value must be explicitly
unboxed to its original value-type. Even this throws InvalidCastException:

int n = 1;
object o = n;
uint u = (uint)o;

Reference: http://tinyurl.com/2d28h
 
Thanks Guys
I was aware that it was an object and not an int but not sure on why the
cast was failing.
Thanks for the advice and link.
Cheers
JB
 
Back
Top