Skip to main content
GameDev.net gamedev.net
🔒 Locked

why box/unbox?

Started by dusty_one Jul 22, 2007 at 8:07 PM 1 replies 2.1k views
Original Post
dusty_one
dusty_one
Concepts aren't my problem right now, but rather usage of concepts. I understand boxing/unboxing, but I can't come up with a scenario when I'd actually use it. Could someone provide a real world example of when it was useful to box/unbox an object?
TheTroll
TheTroll
The reality once 2.0 introduced generics the use for boxing and unboxing has really dropped.

The biggest use would be if you needed to have an array but you didn't know at the start what the types of the numbers would be. You could box them to put them into object[] and unbox to use them.

theTroll
JWalsh
JWalsh
Boxing/Unboxing is really just the ability to convert between a value-type and a reference-type. This is useful any time you'd like to store data, but aren't sure if the data will be a value-type or reference-type. For example...

Many of the Windows Forms controls have lists of items, such as the ListView. Each item in the list view is a ListViewItem. And, while each ListViewItem has a "Text" property which allows you to store the text that is visible by the user, sometimes you want to associate a special meaning with that item. Such as, unique ID's, indecies into a list, or some other useful bit of information.

To make this possible, each ListViewItem object also has a 'Tag' field. This is of type 'System.Object' which means that it is literally possible to store ANY data type in that field. Now, the creators of the ListView and ListViewItem didn't know what type of data you might want to store, they couldn't give it a type when they created it. By making it as generic as possible, they've made it so that users can store anything they want in that field.

To see what it looks like

ListView myListView = new ListView();ListViewItem myItem = new ListViewItem();myItem.Text = "This is my item";myItem.Tag = 1;  // I'm storing the number 1, which is an index into a second list// Now I add my item to the listmyListView.Items.Add(myItem);// Later on, if someone were to click on my list item //I'd get a reference back to my item, which I can use to recover the tagint specialIndex = (int)(sender as ListViewItem).Tag;


I could have just as easily stored a custom struct, or even a class inside of Tag, but its the fact that all types derive from Object which makes boxing/unboxing possible, and more specifically, that I can treat simple types as compatible with user-defined types.

Cheers!


Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.