Monday 11 August 2014

value type reference type(Boxing Unboxing) heap stack in C#

hi 
friends today i am going to explain some confusing concept specially for freshers in C sharp programming.   

value type:
A value type stores its contents in memory allocated on the stack. For example, in this case the value 42 is stored in an area of memory called the stack.Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.

int x = 42;


reference type:
a reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap.
This memory isn't returned to the heap when a method finishes; it's only reclaimed when C#'s garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.

int[] numbers = new int[10];


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.
ArrayList list = new 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
Please do correct me if something wrong


No comments:

Post a Comment