Friday, February 9, 2007

Boxing and Unboxing

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;
4: Console.WriteLine(o);
5: i = (int)o; // explicit unboxing
6: o = 10;
7: Console.WriteLine(i);

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.

3 comments:

Anonymous said...

Interesting. Posted a sample program that illustrates the immutability of boxed value types in C#: http://www.youredoingitwrong.mee.nu/relearning_boxing

Anonymous said...

Excellent, but last block in diagram u r showing, o pointing to 10 thats ok, but why have u showed 5 also near by 10

Anonymous said...

It's been awhile but since the author never answered the last question, I thought I'd give it a shot.

To be more precise, the 5 is shown near the 10 *without* an arrow pointing to it to show that it still exists but does not have a reference to it, which ought to be garbage collected later.