Why does double d = (double)((object)1.2F); result in a System.InvalidCastException?
Polls are open ;-)
PingBack from http://msdnrss.thecoderblogs.com/2007/10/08/do-you-know-your-language-the-tiny-c-quiz/
Has it something to do with boxing? The value is boxed with the "object" cast, and then the clr is not able to unbox it?
Because floats are not doubles ;-)
1.2F (float) is boxed. Unboxing must be done to the same type when using value types.
double d = (double)(float)((object)1.2F); - explicit cast
double d = (float)((object)1.2F); - implicit cast
The reason this cast fails is because when you convert from float to double you loose precision/accuracy. Float has a precision of 7 digists and double has a precision of 15 digits.
In my above comment i was mentioning about the problme with cast from double to float.(sorry for the error)
Now answer to your question:
The reason this cast fails is because when you convert from float to double you do not have the precision/accuracy of double and thus the compiler does not know how to represent the double accurately . Float has a precision of 7 digits and double has a precision of 15 digits.
@Ankit Dass - converting from float to double is safe. You put 7 digits in 15 digits and you loose just some memory. Converting from double to float can cause loss of precision (bigger precision into smaller precision).
The code can be easy translated to:
double a = 1.2F;
It will compile/run without errors.
In VS2005 it does not cause an error.
Where is the quiz?
I do not even get an error when I do this
double d = (float)((object)1.2);
(note that I also omitted the 'F' after 1.2
not even this
double d = (double)(object)(string)((object)1.2F);
Forget my last post.
I mixed "exception" with "compilation error".
The reason is because the unbox concept in .NET requires the "unboxing" type to match the "boxed" source type i.e if an "int" is boxed, an "int" should be unboxed.
To demonstrate this point, use the following code:
byte b = 12;
object o = b; // a BYTE type is boxed
int i = (int)o; // InvalidCastException because a byte is NOT an int, EVEN THOUGH a byte CAN fit into an int!
// the correct code should be
object o = b;
int i = (int)((byte)o);
PS: consider also that precision COULD be lost as the previous posts have already mentioned when going from large to small values types
You can't un-box and cast in the same statement.