Monday, June 05, 2006


I'm a big fan of OO.


So, I always like to do things in an OO way. This includes things writing statements like:


in preference to:

object1 == object2

But I recently discovered that this will cause boxing if either object1 or object2 is a value type. And we should all try to avoid boxing.

Another subtle boxing issue can be in the form of:

MessageBox.Show("Today's Date: " + DateTime.Now);

In this statement, the DateTime value has to be boxed to allow it to be appended to the string. The way to avoid this is:

MessageBox.Show("Today's Date: " + DateTime.Now.ToString());

Simple really. This is the same for all Value Types.

If you want to know if there is boxing in your application, then use either ILDASM or Reflector and look for a box call in the IL. I don't know of a tool that will scan all of your files for boxing. I'm sure that there's gotta be one out there...

No comments: