Boxing Scenario

Why is boxing needed? In which scenario does it happen and what does it come to solve?

  • Every type is either a reference type or a value type
  • object is a reference type - refers to an object in the heap
  • int is a value type - it is allocated in the stack
  • Every type, including int derives from object
  • Up casting (converting up the inheritance hierarchy) is legal by definition
  • What happens when we cast from int to object?
  • An object must refer to the heap, but the int is in the stack!
  • The solution is ... BOXING

I'd like to discuss with you a concept known as boxing. But before I get into the details of boxing, let's review some points from earlier in this module.

First of all, every type in .NET is either a value type or a reference type.

Object is a reference type - it always refers to something in the heap.

int for example is a value type, right? So it's allocated in the stack.

Every type in .NET and that includes int, derives from Object.

We also know that up-casting is always legal.

Now, what happens when we want to cast from int to object? It is legal, because it's up-casting.

What we are trying to obtain by this cast is an object reference that refers to something in the stack, because int resides in the stack. But that can never happen! A reference type always refers to something in the heap, never in the stack! So what's going to happen now? We know that we can do the up-casting because up-casting is always legal, so what's going to happen?? And the answer is... You guessed right! Boxing!