Boxing and Unboxing
Boxing means to store a type as an object. The type can later be cast back to its original type with the original
type information intact.
This is particularly useful with arrays, since objects of any type can be stored in an array of objects
(since all types are derived from the object type).
For example, the following is legal code, and creates an array of objects that are assigned three different
types (but all, of course, are objects once they are stored in the array):
int theInt; string theString; Button1 button1;
object [] stuff = new object [3];
stuff [0] = theInt;
stuff [1] = theString;
stuff [2] = button1;
What has actually happened is that the various types have been implicitly converted to type object. However,
the extended information relating to the derived type has been preserved (“boxing”).
To reverse the process, and “unbox” the types stored as objects, you need to explicitly cast the element
of the object array to the original type. For example:
int newInt = (int) stuff [0];
string newString = (string) stuff [1];
Button button2 = (Button) stuff [2];
|