Sep 16

Unboxing: is it really the opposite of boxing?

Posted in Basics C#      Comments Off on Unboxing: is it really the opposite of boxing?

[Update: Thanks to JPC for finding (yet!) another error in my post]

Yes…well, it is, but it’s cheaper (as we’ll see). As we’ve seen in the previous post, we can convert a value type instance into a reference type instance through an operation known as boxing. Unboxing lets you convert a reference type into a value type (if the reference type was originally obtained through a boxing operation, that is). We’ve already seen an unboxing operation in the previous post (though I really didn’t mention it at the time):

var std2 = (Student)cll[0];

In the previous snippet, we’re converting the reference type instance obtained through boxing into a value type instance (notice the cast operator). The algorithm used for unboxing involve the following steps:

  1. the first thing required is obtaining the reference type. Then, the reference is checked against null and if it is null, you’ll end up with an exception. If it’s not, then an additional check is performed: the type of the boxed instance is checked. If it doesn’t match the type indicated in the unboxing operation, you’ll get a different type of exception: in this case, an InvalidCastException is thrown.
  2. If we reach this step, then the fields values are copied from the managed heap to the newly allocated space in the stack.

Notice that the unboxed value is *always* copied into *newly* allocated space in the stack.  IN other words,in the example of the previous post,we’ve ended up with two different Student instances on the stack. And that’s why you’re wrong if you assumed that the next snippet (also copied from the example in the previous post) would print the value true:

Console.WriteLine(std.Name == std2.Name);

As you can see, unboxing is relatively cheaper than boxing. It goes without saying that boxing and unboxing won’t help to improve the performance of your application, so you better pay attention to your code. Now, that you understand boxing and unboxing, we’re ready for the next phase: understand all the scenarios where boxing happens. Stay tuned for more.