Monday, November 29, 2010

Boxing - Good News

In my previous post I mumbled about how value types were good for performance (of code – stop sniggering) but that isn’t the end of their story.

All value types derive from System.ValueType which derives from System.Object so anytime you have to use a method that only takes a parameter of object rather than the value type you want to pass it - just cast your value type to object. No problem.

Oh, hang on, there is a slight problem, an object variable is a pointer to the instance of a type on the managed heap and we've only got a value type on the thread stack - um.............. Fortunately the clever coders in Microsoft have solved the problem, anytime you need to use your value type instance as an object the Common Language Runtime (CLR) will wrap it into a reference type instance on the managed heap and give you a pointer to it. The process for doing this is what I like to call Boxing (If you don’t watch Miranda you didn’t get the joke).

The good news is boxing is implicit, all I need to do is add a line of code to my ValueType loop from the previous post that says:

object o = vt;

and the value type has been boxed and you have a pointer (o) to a  reference type instance on the managed heap. Boxing is great! The next post will be Boxing - Bad News where it is possible the level of greatness will reduce.

No comments:

Post a Comment