Program Output RRS feed

  • Question

  • User1904516115 posted

    Why following program is throwing InvalidCastException?

    string s = "12";
    object o = s;
    int i = (int)o;//InvalidCastException

    int i = 12;
    object o = i;
    long j = (long)o;//InvalidCastException

    Saturday, September 24, 2016 3:32 AM


  • User36583972 posted

    Hi vinodkpasi,

    You can find the following error message.

    Additional information: Specified cast is not valid.

    It is caused by the limitations of an unboxing cast. You can use Console.WriteLine(Convert.ToInt32(o)) rather than (int)o.  It takes an object and supports all of the types. You can refer the following link.

    Representation and Identity:


    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 24, 2016 5:08 AM