Tuesday, 25 August 2015

Boxing and Unboxing

Boxing is name given to the process whereby a value type is converted into a reference type. When you box a variable, you are creating a reference variable that points to a new copy on the heap. The reference variable is an object, and therefore can use all the methods that every object inherits, such as, ToString(). 
This is what happens in the following code:
int i = 67;                              // i is a value type 
object o = i;                            // i is boxed
System.Console.WriteLine(i.ToString());  // i is boxed

You will encounter unboxing when you use classes designed for use with objects: for example, using an ArrayList to store integers. When you store an integer in the ArrayList, it's boxed. When you retrieve an integer, it must be unboxed.
This is what happens in the following code:
System.Collections.ArrayList list = new System.Collections.ArrayList();
                                    // list is a reference type 
int n = 67;                         // n is a value type
list.Add(n);                       // n is boxed
n = (int)list[0];                  // list[0] is unboxed
Summary
In this article I try to clear concept of Boxing and Unboxing. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

No comments:

Post a Comment