Boxing and Unboxing
You may have observed that types of a class that are derived from a class can assigned to
an array of that class, even though, as I mentioned above, an array is used to store objects
of the same type. Specifically, 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:
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. (If you look at the members of each element of the stuff [] array, you’ll find the
members of an object type.) However, the extended information relating to the derived type
has been preserved. This is called “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];
|
|
Search Engine Optimization
 
Syndication Viewer
Our Web host:
IX WebHosting
|