Challenge - 5 Problems
Boxing and Unboxing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this boxing and unboxing code?
Consider the following C# code snippet. What will it print when run?
C Sharp (C#)
int x = 10; object obj = x; // boxing int y = (int)obj; // unboxing Console.WriteLine(y);
Attempts:
2 left
💡 Hint
Boxing stores the value type inside an object. Unboxing extracts it back.
✗ Incorrect
The integer 10 is boxed into an object. Then it is unboxed back to int y. Printing y outputs 10.
❓ Predict Output
intermediate2:00remaining
What happens if unboxing to wrong type?
What will this C# code print or do when executed?
C Sharp (C#)
int x = 5; object obj = x; // boxing long y = (long)obj; // unboxing to wrong type Console.WriteLine(y);
Attempts:
2 left
💡 Hint
Unboxing requires exact type match.
✗ Incorrect
Unboxing to a different value type than originally boxed causes InvalidCastException at runtime.
🔧 Debug
advanced2:00remaining
Why does this code cause a runtime error?
Examine the code below. Why does it throw an exception at runtime?
C Sharp (C#)
object obj = 42; // boxing int short s = (short)obj; // unboxing to short Console.WriteLine(s);
Attempts:
2 left
💡 Hint
Unboxing must match the original boxed type exactly.
✗ Incorrect
The object holds a boxed int. Unboxing to short is invalid even if int fits in short. This causes InvalidCastException.
🧠 Conceptual
advanced2:00remaining
What is the main cost of boxing in C#?
Why is boxing considered costly in C# programs?
Attempts:
2 left
💡 Hint
Think about what happens when a value type is boxed.
✗ Incorrect
Boxing creates a new object on the heap and copies the value inside it, which uses extra memory and CPU time.
❓ Predict Output
expert2:00remaining
What is the output of this mixed boxing and unboxing code?
Analyze the following C# code and determine its output:
C Sharp (C#)
object obj = 123; int a = (int)obj; obj = a + 1; int b = (int)obj; Console.WriteLine(a + "," + b);
Attempts:
2 left
💡 Hint
Remember boxing creates a new object each time.
✗ Incorrect
Initially obj boxes 123. a unboxes 123. Then obj is assigned a+1 (124) boxed. b unboxes 124. Output is "123,124".