Challenge - 5 Problems
Boxing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of boxing with value types
What is the output of this C# code snippet involving boxing and unboxing?
C Sharp (C#)
int x = 10; object o = x; // boxing int y = (int)o; // unboxing Console.WriteLine(y + 5);
Attempts:
2 left
💡 Hint
Remember that boxing copies the value type into an object and unboxing extracts it back.
✗ Incorrect
Boxing copies the integer value 10 into an object. Unboxing extracts the integer back. Adding 5 results in 15.
❓ Predict Output
intermediate2:00remaining
Effect of boxing on performance counters
What will be printed by this code that counts boxing operations?
C Sharp (C#)
int count = 0; object Box(int x) { count++; return x; } int a = 5; object o1 = Box(a); object o2 = Box(a + 1); Console.WriteLine(count);
Attempts:
2 left
💡 Hint
Each time an int is assigned to object, boxing occurs.
✗ Incorrect
Both calls to Box receive an int and return an object, so boxing happens twice, incrementing count twice.
🔧 Debug
advanced2:00remaining
Identify the performance issue caused by boxing
Which line in this code causes boxing and may degrade performance?
C Sharp (C#)
List<int> numbers = new List<int> {1, 2, 3}; foreach (object obj in numbers) { Console.WriteLine(obj); }
Attempts:
2 left
💡 Hint
Check the type used in the foreach loop variable.
✗ Incorrect
The foreach uses object to iterate over a List. Each int is boxed to object causing performance overhead.
❓ Predict Output
advanced2:00remaining
Output when boxing affects method overload resolution
What is the output of this code involving method overloads and boxing?
C Sharp (C#)
void Print(int x) { Console.WriteLine("Int: " + x); } void Print(object o) { Console.WriteLine("Object: " + o); } int val = 7; Print(val);
Attempts:
2 left
💡 Hint
Method overload resolution prefers exact type matches over boxing.
✗ Incorrect
The Print(int) method is chosen because it matches the argument type exactly, avoiding boxing.
🧠 Conceptual
expert3:00remaining
Why does boxing impact performance negatively?
Which of the following best explains why boxing can degrade performance in C#?
Attempts:
2 left
💡 Hint
Think about what happens when a value type is boxed.
✗ Incorrect
Boxing copies the value type into a new object on the heap, which uses more memory and CPU time, slowing performance.