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):
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:
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:
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.
Original Post: Unboxing: is it really the opposite of boxing?
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.