Quiz: How Box Savvy Are You?

The following section of code gives different scenarios. Look through them and decide which ones involve boxing, and which ones don't. Some scenarios have more than one location to examine (B, for example).

// Scenario 1
int total = 35;
DateTime date = DateTime.Now;
string s = String.Format("Your total was {0} on {1}", total, date);

// Scenario B
Hashtable t = new Hashtable();
t.Add(0, "zero");
t.Add(1, "one");

// Scenario c
DateTime d = DateTime.Now;
String s = d.ToString();

// Scenario IV
int[] a = new int[2];
a[0] = 33;
 
// Scenario 101
ArrayList a = new ArrayList();
a.Add(33);

// Scenario vi
MyStruct s = new MyStruct(15);
IProcess ip = (IProcess) s;
ip.Process();

Answers

Read through the answers and keep track of your score.

Scenario 1

String.Format() takes a string as the first parameter, with object as the second and third parameters. Both int and DateTime are value types, so they will both be boxed for the second and third parameters. String.Format() will take these parameters, then call object.ToString() on each of them to convert them to a string representation. One point for knowing that int would be boxed, one point for DateTime being boxed.

Scenario B

Hashtable.Add() takes two parameters, one for the key, one for the value. Both of them are of type object. The value passed for the key is an integer, so it must be boxed to be passed as an object. The value passed for the value is a string, which is a reference type, so there is no boxing of the string. One point for getting each right.

Scenario c

This is a trick scenario. One of the points of being able to box is so that virtual functions can be called on value types, and ToString() is a virtual function on object, so it would appear that d would be boxed when ToString() is called. However, we haven't used d in a situation where it would get converted to an object, so a box isn't required. The compiler knows that a variable of type DateTime can only be that type (it can't be a derived type, since there are no derived value types), so it can call DateTime.ToString() directly and set the "this" reference to point to the d instance on the stack. One point for getting this correct.

Scenario IV

Arrays in the CLR store their values directly. An int array with five elements, for example, allocates enough space to store five ints, not five objects. One point if you said that there is no boxing here.

Scenario 101

ArrayList.Add() takes an object as a parameter, so the integer 33 will be boxed. One point if you got it correct.

Scenario vi

Interfaces are reference types, so when you cast a value type to an interface that it implements, the value type must be boxed. One point if you knew this.

Score Yourself

Add up your score and use the following table to see how box savvy you are:

Score Description
8 The epitome of box savviness
6-7 Savvy, but inconsistent
3-5 Aspiring to savvy
1-2 Find a savvy teacher
0 Stick to a lunch box