0
0
C Sharp (C#)programming~20 mins

Boxing and unboxing execution in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Boxing and Unboxing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
A10
B0
CCompilation error
DInvalidCastException at runtime
Attempts:
2 left
💡 Hint
Boxing stores the value type inside an object. Unboxing extracts it back.
Predict Output
intermediate
2: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);
A5
BInvalidCastException at runtime
CCompilation error
D0
Attempts:
2 left
💡 Hint
Unboxing requires exact type match.
🔧 Debug
advanced
2: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);
ABecause boxing failed due to missing cast
BBecause Console.WriteLine cannot print short
CBecause short cannot hold int values
DBecause unboxing requires exact type, not convertible types
Attempts:
2 left
💡 Hint
Unboxing must match the original boxed type exactly.
🧠 Conceptual
advanced
2:00remaining
What is the main cost of boxing in C#?
Why is boxing considered costly in C# programs?
ABecause it modifies the original variable's value
BBecause it changes the value type to a reference type permanently
CBecause it creates a new object on the heap and copies the value
DBecause it requires special compiler directives
Attempts:
2 left
💡 Hint
Think about what happens when a value type is boxed.
Predict Output
expert
2: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);
A123,124
B124,124
C123,123
DInvalidCastException at runtime
Attempts:
2 left
💡 Hint
Remember boxing creates a new object each time.