Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Boxing and unboxing execution in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Boxing and unboxing execution
Value type variable
↓
Boxing: Wrap value in object
↓
Reference type variable holds boxed value
↓
Unboxing: Extract value from object
↓
Value type variable restored
Boxing wraps a value type into an object; unboxing extracts the value back from the object.
Execution Sample
C Sharp (C#)
int x = 123;
object o = x; // boxing
int y = (int)o; // unboxing
Console.WriteLine(y);
This code boxes an int into an object, then unboxes it back to int and prints it.
Execution Table
StepActionVariableValue/StateNotes
1Declare int xx123x holds value type 123
2Box x into object ooBoxed 123o holds reference to boxed int 123
3Unbox o to int yy123y gets value extracted from boxed object
4Print yOutput123Output shows unboxed value
5End--Execution ends
💡 Program ends after printing the unboxed value 123
Variable Tracker
VariableStartAfter BoxingAfter UnboxingFinal
x123123123123
onullBoxed 123Boxed 123Boxed 123
yundefinedundefined123123
Key Moments - 3 Insights
Why does boxing create a new object instead of just copying the value?
Boxing wraps the value type inside a reference type object on the heap, so it must create a new object to hold the value separately, as shown in step 2 of the execution_table.
What happens if you try to unbox to the wrong type?
Unboxing to the wrong type causes an InvalidCastException at runtime because the object holds a boxed value of a specific type, as implied in step 3 where unboxing must match the original type.
Does the original value type variable change during boxing or unboxing?
No, the original value type variable remains unchanged throughout, as seen in the variable_tracker where 'x' stays 123 after boxing and unboxing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'o' after step 2?
Anull
B123
CBoxed 123
Dundefined
💡 Hint
Check the 'Value/State' column for variable 'o' at step 2 in execution_table.
At which step does the variable 'y' get its value assigned?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Variable' columns in execution_table to see when 'y' is assigned.
If we skip boxing and assign 'x' directly to 'o' without casting, what would happen?
ACompile error
BBoxing still happens automatically
CUnboxing happens instead
Do becomes null
💡 Hint
In C#, assigning a value type to an object variable causes boxing automatically, as shown in step 2.
Concept Snapshot
Boxing: Convert value type to object (reference type).
Unboxing: Extract value type from boxed object.
Boxing creates a new object on the heap.
Unboxing requires explicit cast to original type.
Incorrect unboxing causes runtime error.
Original value type variable stays unchanged.
Full Transcript
This example shows boxing and unboxing in C#. First, an int variable x is declared with value 123. Then x is boxed into an object o, which means a new object is created on the heap holding the value 123. Next, the object o is unboxed back to an int y by casting. Finally, y is printed, showing 123. The original variable x remains unchanged throughout. Boxing wraps the value type into a reference type object, and unboxing extracts the value back. Unboxing must match the original type or it causes an error. This trace helps visualize how values move between value and reference types in C#.

Practice

(1/5)
1. What happens during boxing in C#?
easy
A. A value type is converted to an object type.
B. An object type is converted to a value type.
C. A reference type is converted to a value type.
D. A value type is converted to a string.

Solution

  1. Step 1: Understand boxing concept

    Boxing means wrapping a value type (like int) inside an object so it can be treated as an object.
  2. Step 2: Identify the conversion direction

    Boxing converts a value type to an object type, not the other way around.
  3. Final Answer:

    A value type is converted to an object type. -> Option A
  4. Quick Check:

    Boxing = value type to object [OK]
Hint: Boxing wraps value types as objects [OK]
Common Mistakes:
  • Confusing boxing with unboxing
  • Thinking boxing converts to string
  • Mixing up value and reference types
2. Which of the following is the correct syntax to unbox an object to an int in C#?
easy
A. int x = obj.ToInt();
B. int x = obj as int;
C. int x = Convert.ToInt32(obj);
D. int x = (int)obj;

Solution

  1. Step 1: Recall unboxing syntax

    Unboxing requires an explicit cast from object to the original value type.
  2. Step 2: Check each option

    int x = (int)obj; uses explicit cast (int)obj which is correct. int x = obj as int; uses 'as' which works only for reference types. int x = Convert.ToInt32(obj); converts but is not unboxing. int x = obj.ToInt(); is invalid syntax.
  3. Final Answer:

    int x = (int)obj; -> Option D
  4. Quick Check:

    Unboxing = explicit cast (int)obj [OK]
Hint: Unboxing needs explicit cast (int)obj [OK]
Common Mistakes:
  • Using 'as' keyword for unboxing
  • Using Convert.ToInt32 instead of cast
  • Calling non-existent methods like ToInt()
3. What is the output of the following C# code?
int a = 10;
object obj = a; // boxing
int b = (int)obj; // unboxing
b += 5;
Console.WriteLine(a);
medium
A. 15
B. 10
C. 5
D. Compilation error

Solution

  1. Step 1: Understand boxing and unboxing here

    Variable 'a' is boxed into 'obj'. Then 'obj' is unboxed into 'b'. 'b' is a separate copy.
  2. Step 2: Check value changes

    Incrementing 'b' by 5 does not affect 'a'. So 'a' remains 10.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Boxing copies value; original stays 10 [OK]
Hint: Boxing copies value; original unchanged [OK]
Common Mistakes:
  • Assuming 'a' changes when 'b' changes
  • Confusing reference and value types
  • Thinking boxing links variables
4. Identify the error in this C# code snippet:
object obj = 123;
long l = (long)obj;
Console.WriteLine(l);
medium
A. Invalid cast exception at runtime
B. Compilation error due to missing cast
C. No error, prints 123
D. Null reference exception

Solution

  1. Step 1: Analyze boxing and unboxing types

    Boxing stores an int (123) in obj. Unboxing must cast back to int, not long.
  2. Step 2: Understand runtime behavior

    Trying to unbox as long causes InvalidCastException because obj holds int, not long.
  3. Final Answer:

    Invalid cast exception at runtime -> Option A
  4. Quick Check:

    Unboxing type mismatch causes runtime error [OK]
Hint: Unbox only to original value type [OK]
Common Mistakes:
  • Casting to different value type than boxed
  • Expecting compile-time error instead of runtime
  • Ignoring boxing type stored
5. Given a list of integers boxed as objects, how can you sum their values correctly in C#?
List<object> list = new List<object> { 1, 2, 3, 4 };

Which code snippet correctly sums the integers?
hard
A. int sum = 0; foreach (int x in list) sum += x;
B. int sum = 0; foreach (object o in list) sum += (o as int);
C. int sum = 0; foreach (object o in list) sum += (int)o;
D. int sum = list.Sum();

Solution

  1. Step 1: Understand list content and types

    List contains objects boxed from ints. To sum, unbox each object to int.
  2. Step 2: Evaluate each option

    A: int sum = 0; foreach (int x in list) sum += x; compile error - cannot implicitly convert object to int.
    B: int sum = 0; foreach (object o in list) sum += (o as int); compile error - 'as' cannot be used with non-nullable value types.
    C: int sum = list.Sum(); fails because list is List<object>, no Sum() overload.
    D: int sum = 0; foreach (object o in list) sum += (int)o; unboxes correctly with (int)o.
  3. Final Answer:

    int sum = 0; foreach (object o in list) sum += (int)o; -> Option C
  4. Quick Check:

    Unbox each object with (int)o to sum [OK]
Hint: Unbox each object with (int)o before summing [OK]
Common Mistakes:
  • Trying to foreach as int directly
  • Using Sum() on List<object>
  • Using 'as' operator for unboxing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard