Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
int n = 5;
object box = n;
Console.WriteLine(box);
long big = (long)box;
Console.WriteLine(big);5, then an InvalidCastException
- Expecting
5twice: unboxing is not a number conversion; a boxedintcomes out asint, not aslong, so(long)boxthrows. Writelong big = (int)box;. - Expecting a compile error: the compiler cannot see what an
objectholds, so the cast is checked only when the program reaches that line.
- How would you change the line with
(long)boxso that the program prints5twice? - Why does
object box = n;need no cast, whileint back = box;does not compile?