Casting object that has short value to int in C# -


consider code:

private static void main(string[] args) {     short age = 123;     object ageobject = age;     //var intage = (int)ageobject;//specified cast not valid.     int newage= (short)intage;     console.readline(); } 

i have assign short value object , again cast int, when try this: var intage = (int)ageobject; : specified cast not valid. don't know why?

after search in google found should cast short , assign int:int newage= (short)intage;

why should casting short , assign int?

why compiler has behavior?

the failure runtime error.

the reason age value has been boxed object; unboxing incorrect type (int) failure - it's short.

the cast on line you've commented out unboxing operation, not cast.


Comments