a blog for those who code

Saturday, 16 August 2014

C# Boxing and Unboxing

In this post we will show you what is boxing and unboxing in C#. Before continuing with this post you can look into the Difference between Value Type and Reference Type.

Boxing is implicit conversion of value type to a reference type whereas Unboxing is explicit conversion of same reference type (boxed by value type) back to value type. In the process of boxing memory of value type is allocated on the heap rather than stack and the value type's field are copied to the newly allocated heap memory. In the process of unboxing, the memory is removed from the heap and its assigned to stack.

So, you must be wondering what is the scenario when we have to box a value type. So, lets take an example.
ArrayList arr = new ArrayList();
int a = 1;
arr.Add(a);


The Add Method of ArrayList will look like - public virtual int Add(Object value)
where value's Type is System.Object which can be null.

So, just think for a moment using "arr.Add(a);" have we added an integer variable or the address of integer variable. The answer is at run time the Integer value type is converted to a reference type (i.e. boxing), and the memory address of the boxed integer variable is passed to the Add method of ArrayList.

Unboxing is opposite of boxing. At first, the address of the boxed value type is obtained then the values are copied from the heap to the stack.
ArrayList arr = new ArrayList();
int a = 1;
arr.Add(a); // Boxing
int b = (int) arr[0]; // UnBoxing


While using Boxing and Unboxing you should note the following points,
1. If you try to unbox a reference to the boxed value type to an incompatible value type, you will get InvalidCastException.
ArrayList arr = new ArrayList();
int a = 1;
arr.Add(a);
bool b = (bool) arr[0]; // InvalidCastException Error


2. Suppose you have boxed a value type, a reference to the boxed value type is obtained. If by any chance that reference becomed null then you might get NullReferenceException.
ArrayList arr = new ArrayList();
int a = 1;
arr.Add(a);
arr[0] = null;
int b = (int) arr[0]; // NullReferenceException


Please Like and Share the Blog, if you find it interesting and helpful.

You may also like :

Casting with is and as operators in C#
Definition and Use of Indexes
Dot Net : All types are derived from System.Object
All you want to know about Common Language Run Time (CLR)
Null Coalescing operator (??) in C#
All about MongoDB Collections
How to improve Asp.Net Application Performance - Part 2
Write text files without Byte Order Mark.
Dictionary Vs Hashtable
C# NullReferenceException : Object reference not set to an instance of an object

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License