Boxing and Unboxing - And Some Solutions

Created: December 23, 2014 Tagged As: C#, Language Share:

Everything in Microsoft.net languages derives from System.Object (or object in C#). Therefore, this is the base type that is often use to store variables (think Session, ViewState, Array). That makes for a nice, easy to follow structure. And you can always cast an object to its actual type; i.e., int i = (int)o.

Did you ever think that this cast (called unboxing) takes processing power. The opposite (called boxing, as in object o = i) is also true. Here is a decent reference from Microsoft on the subject: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx.

So what can a conscientious programmer do? I recommend the following:

  1. If you intend to use a boxed variable more than once, unbox it before using it as in:
    Person p = (Person)p;
    p.FirstName="Brian";
    p.LastName="Limkemann";
  2. Use Generics whenever possible to force the compiler to eliminate boxing / unboxing. Theere are many other advantages as well - look for an upcoming article on Generics.
  3. Use the Nullable type, especially when mimicking database columns. For example, rather than using an object to store either null, or an Integer, use int?.