Roadmap › C# Language — Basics to Advanced › Module: Types in Depth
Lessons in this course (38)

17. Boxing and unboxing

Basic★ Must knowLesson 17 of 38

Boxing wraps a value type in an object on the heap; unboxing extracts it back with an explicit cast.

csharp
int n = 42;
object o = n;        // boxing: heap allocation + copy
int m = (int)o;      // unboxing: type check + copy
// long l = (long)o; // InvalidCastException — must unbox to the exact type

var old = new System.Collections.ArrayList();
old.Add(1);          // boxes — avoid non-generic collections
var modern = new List<int>();
modern.Add(1);       // no boxing — generics

Cost: an allocation and later GC work. Generics (C# 2.0) removed most boxing.