Random collection of notes, personal tips, and general things.

Bits & Bytes

  • Follow Us on Twitter!
  • LinkedIn

A not so obvious boxing

Boxing is the term used for when a type is converted into an object without an explicit cast.  Sometimes its pretty obvious when that's occurring, such as;

object x = 5;

And other times, it isn't all that obvious that its occurring.

Unboxing is the reverse (however an explicit cast is required when unboxing).  Boxing and unboxing add just that little bit of additional overhead in terms of processing, and in cases can cause bugs when you're not aware you're working with a boxed value.

One slightly less obvious case of boxing that I just came across is when using string.format & the new string interpolation replacement.

Have a look at the simple code below & the corresponding IL

line 33 turns into the IL listed from 149 to 155.  At 151 and 153 there's two box operations to box the int32 values that are being passed to the string format.

Same also if the string interpolation feature is used instead

If the code is changed slightly to use the ToString() method on the int values to explicitly convert them to strings first, the two box operations get removed.

I'm sure its one of those 'well, its kind of obvious when you think about it' situations - I'd just never thought to think about how the parameters for string.format got handled.