CSharpFeeds - All your C# feeds in one place.

Sponsors

Thursday, September 16, 2010

Unboxing: is it really the opposite of boxing?

by luisabreu via LA.NET [EN] on 9/16/2010 10:22:00 PM

[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.


email it!bookmark it!digg it!

Original Post: Unboxing: is it really the opposite of boxing?

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us