CodeBlanks Logo Icon CodeBlanks

Value and reference types

C# course · Beginner · Lesson 17/116

Learn the core difference between value types and reference types.

Boxing

Boxing wraps a value type into an object (or interface) box. The value is copied from the stack to the heap, and the reference points to that address.

Example: object box = 42; The int value is placed on the heap and box points to it. Boxing happens automatically and implicitly; you write no extra code.

Boxing is convenient but slow because it allocates heap memory. Whenever possible, use the value type directly for better speed.

Unboxing and performance

Unboxing extracts a boxed object back into a value type. It is the reverse of boxing but requires an explicit cast.

Example: int n = (int)box; The (int) parentheses tell the compiler the type explicitly. Unboxing with the wrong type throws an InvalidCastException.

Boxing and unboxing together are costly; both do heap work. For now, remember that unboxing needs an explicit cast.

Exercise Box and unbox a value

Assign 42 to an object box variable (boxing occurs). Extract the value back with int value = (int)box; (unboxing). Then print value with Console.WriteLine.

Show example solution
object box = 42; int value = (int)box; Console.WriteLine(value);
Example solution:
using System;
class Program {
    static void Main() {
        object box = 42;
        int value = (int)box;
        Console.WriteLine(value);
    }
}

Test yourself

  1. Match each conversion to its name

    int to object
    boxing
    object to int
    unboxing
    int to double
    implicit
    string to int
    Parse
  2. Which line causes boxing?

    • double d = 5;
    • object o = 5;
    • int n = (int)5.0;
    • string s = "5";
    Show answer

    object o = 5; — Correct! Assigning a value type to object causes boxing.

  3. Unbox an object into an int

    int n = ____ o;
    Show answer
    int n = (int) o;

All lessons in Beginner