Friday, November 19, 2010

Boxing and Unboxing

Boxing is a boring sport; but in the exciting and melodramatic world of programming, boxing is the process of converting a value type to a reference type, or converting a basic datatype (like an integer) to an object.

Unboxing is the opposite of boxing; that is to convert an object to a value type.
Here is an example right off my head:
int x = 5;
object k = x; //or object k = (object) x for explicit boxing

int z;
z= k // k is our boxed type

While boring real life boxing can make you look like a douche (go for Jujitsu instead), boxing in the programming realm can make you look like a life-saving wizard, especially when working on managed programming languages.



You're doing it wrong.



Boxing is needed when a parameter of a function that you need to call is an object, while you need to send a trivial datatype. Want a simple example? Sometimes you need to pass an int value as a string, so you use the ToString() function.

A complex example of boxing usage (besides beating people up) involves boxing trivial types as objects in order to be referenced as delegates.

 Now, what does this have to do with efficiency, you say? Well, boxing is evil as a programming practice, and should be used sparingly. When you box an object, the memory usage can be 20 times that of the trivial datatype, and the process of boxing and unboxing wastes a considerable amount of CPU cycles as opposed to handling trivial datatypes.


"Convert THIS to String!"



In the old days of .NET, people had to use boxing a lot because of ArrayLists, but that is no longer needed as you can use generic collections. 

No comments:

Post a Comment