MediumConcept

What is boxing and unboxing in C# and why does it affect performance?

Technology:
C#
Experience:
Junior,
Mid-level

Quick answer

Boxing converts a value type to object by allocating it on the heap, and unboxing converts it back; both add allocations and casts, so avoid them in hot code paths.

Detailed explanation

Assigning an int to an object variable boxes it: the runtime allocates a new object on the heap and copies the value in. Casting back with (int)obj is unboxing, which checks the type and copies the value out. Boxing in a loop creates garbage that the collector has to clean.

Generics were introduced to avoid this: List<int> stores ints directly, whereas the old ArrayList boxed every item. Watch for hidden boxing when a struct is used as an interface type, or when you pass a value type to a method taking object, such as older string.Format overloads.

Example

csharp
int i = 42;
object boxed = i;        // boxing: heap allocation
int j = (int)boxed;      // unboxing: type check + copy

var list = new List<int>();   // no boxing
list.Add(i);
  • C#Easy

    What is the difference between string and StringBuilder in C#?

    A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

    Intern 路 Junior 路 Performance
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope
  • C#Medium

    How does garbage collection work in C# and when should you use IDisposable?

    The .NET garbage collector automatically frees managed objects that are no longer reachable, organising them into generations 0, 1 and 2 so short-lived objects are collected cheaply, and IDisposable is used to release unmanaged resources such as files and connections promptly.

    Mid-level 路 Senior 路 Memory Management
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals