by luisabreu via LA.NET [EN] on 9/16/2010 9:39:58 PM
As we’ve seen, value types have better performance than reference types because they’re allocated in the stack, they’re not garbage collected nor do they get the extra weight generally associated with reference types. There are, however, some times where we need a “reference to a value object” (yes, I wanted to write “reference to a value object”). In the old days, that would happen whenever you needed a collection of value objects (as you recall, in .NET 1.0/.NET 1.1 there were no generics). Here’s a small example:
Now, and this is important, pay attention to the following snippet:
If you look at the docs, you’ll notice that the Add method expects an Object instance. In other words, it requires a reference type and not a value type. If you go ahead and compile the previous snippet, you won’t get any compilation errors. What’s going on here? What you’re seeing is perfectly normal and it’s called boxing. Boxing allows us to convert a value type into a reference type. Boxing involves a rather simple algorithm:
When the compiler detected that the Add method requires a reference type, it went ahead and applied the previous algorithm in order to transform the value type and pass a reference into the method. In other words, what got added to the cll collection was the reference obtained from step 3 (and not the std variable).
This has lots of implications which might not be obvious at first. For instance, if you think that the following snippet should print true, you’re wrong:
Before getting into why that happens, we need to understand unboxing. Since it’s 22:37 and I still haven’t had my dinner, I’ll leave the unboxing post for later :)
Stay tuned for more!
Original Post: Value types and 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.