Thursday, September 18, 2008

Boxing And Unboxing in C#

1. Boxing is when we convert a value type into reference type,when we are boxing we are creating reference variables which point to a new copy on the heap.

2. Unboxing is when we convert a reference type to a value type.

3. Best example of boxing and unboxing can be while we store integer variable which is a value type in a ArrayList which is a reference type.

4. And when we retrieve the value stored in ArrayList to an integer then we change a reference type to value type ie we do unboxing.

ArrayList myArrayList = new ArrayList();
Int n = 7;
myArrayList.Add(n);//Boxing of n
n = (int)myArrayList[0];//Unboxing of myArrayList[0]


Post a Comment