In previous post we discussed the concept of value types vs. reference types and how two are different. Today we will discuss Boxing and Unboxing.
Boxing and Unboxing
Boxing is the process of converting a value type to a reference type. If you recall from my previous post about Value Types vs. Reference Types, the value types are stored on a stack while the reference types are stored on heap and a pointer to the reference type is stored on the stack.
Let's assume you have the following method..
public void Add(object obj, object obj2)
{
if (obj.GetType() == typeof(string) && obj2.GetType() == typeof(string))
{
//do something...
}
else if (obj.GetType() == typeof(int) && obj2.GetType() ==typeof(int))
{
//do something...
}
}
When you call this method and pass an integer or some other value type variable, it is first boxed, i.e. converted to a reference type and then it is unboxed i.e. converted back to value type before it is used. Boxing is implicit but unboxing is explicit i.e. you must cast the boxed variable back into the value type before you can use it.
Note: The code above is for illustration only and you should try to avoid boxing/unboxing for obvious performance reasons.
Another example of implicit boxing is in the use of an arraylist. For example,
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
Recall that an arraylist is a reference type. When you add an integer to the arraylist, it is then boxed i.e. converted to a reference type and then added to the arraylist. When you need to use the value assigned to this arraylist, it must be unboxed.
int i = (int)(list(0);
No comments:
Post a Comment