After putting together the diagrams for the reference types and value types post it seemed appropriate to follow it up with a visualization of the concepts of boxing and unboxing. This might not be the worlds most glamorous post, but it’s important because boxing and unboxing is one of the problems that generics attempts to solve in C# 2.0, and understanding the problem will help you to know when and why to use the solution.
Basically boxing is copying a value type from the stack to the heap. Unboxing is copying a value type from the heap back to the stack. These two operations are expensive, and can add noticeable delays when they happen frequently.
Consider the following code:
1: int i = 5;
2: object o = i; // implicit Boxing
3: i = 10;
5: i = (int)o; // explicit unboxing
6: o = 10;
Well, first of all can you guess what the WriteLine statements will be? If so then you probably already understand boxing. Regardless, hopefully the diagram below will help.
I’ve tried to clarify a little further from previous diagrams what’s on the stack and what’s on the heap. In the diagram items on the stack have outlines in maroon while items on the heap have dash lines and a gray background (click to enlarge).
Figured out the answer? It’ll output 5 twice, which is perhaps a little counter-intuitive, but key to understanding boxing and unboxing.