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

  1. Thomas says:

    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?

  2. Henk de Koning says:

    Because floats are not doubles 😉

  3. mihai stanciu says:

    1.2F (float) is boxed. Unboxing must be done to the same type when using value types.

    Correct:

    double d = (double)(float)((object)1.2F); – explicit cast

    double d = (float)((object)1.2F); – implicit cast

  4. Ankit Dass says:

    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.

  5. Ankit Dass says:

    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.

  6. mihai stanciu says:

    @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.

  7. Thomas S says:

    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.

  8. Thomas S. says:

    Forget my last post.

    I mixed "exception" with "compilation error".

  9. michaelj says:

    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

  10. Rojo Orbalino says:

    You can't un-box and cast in the same statement.