Freigeben über


Do you know your language? The tiny C# quiz :-)

Why does double d = (double)((object)1.2F); result in a System.InvalidCastException?

Polls are open ;-)

Daniel

Comments

  • Anonymous
    October 07, 2007
    PingBack from http://msdnrss.thecoderblogs.com/2007/10/08/do-you-know-your-language-the-tiny-c-quiz/

  • Anonymous
    October 08, 2007
    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?

  • Anonymous
    October 08, 2007
    Because floats are not doubles ;-)

  • Anonymous
    October 08, 2007
    The comment has been removed

  • Anonymous
    October 08, 2007
    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.

  • Anonymous
    October 08, 2007
    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.

  • Anonymous
    October 08, 2007
    @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.

  • Anonymous
    October 08, 2007
    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); TS.

  • Anonymous
    October 08, 2007
    Forget my last post. I mixed "exception" with "compilation error".

  • Anonymous
    October 08, 2007
    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 byte b = 12; 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

  • Anonymous
    October 31, 2012
    The comment has been removed