Boxing and Unboxing in C#

Posted by Techie Cocktail | 10:08 PM | | 0 comments »

C# offers Value types and Reference types. Value types are stored on stack whereas Reference types are stored on heap. The conversion from Value types to Reference types is called boxing and the conversion from Reference types to Value types is called unboxing.

Boxing and Unboxing is possible because of the CTS (Common Type System) in .net. As all types (value/reference) derive from the common 'object' type, it becomes possible to box and unbox between value and reference types.

Quite often we box and unbox variable when we store value types to ArrayList which is a reference type. This causes performance issues in some situation. Check the below example for ArrayList demonstration.


ArrayList arrLst = new ArrayList();
int i = 100;

//Boxing
arrLst.Add(i);

//Unboxing
i = (int)arrLst[0];


Below is the another example to demonstrate boxing and unboxing.

Example

Boxing
int a=7;
object o;
o=a;

Unboxing
int a;
int b;
object o;
b=(int)o;

0 comments