Braintique.com header
Left Navigation Bar

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];

Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write