BOXING AND UNBOXING IN C#

Boxing and unboxing are two concept used in c type . They are used to create a link between the two major data type in c# - value type and reference type , All value type store in stack , but in some situation they need to be reference as heap .  Science reference type are stored in heap we can convert the value type into reference type . This conversion is called "boxing" .

                            Boxing is needful in situation when a value type is converted into a base object or an interface . The CLR ( Common language run-time ) then convert the value type to the reference type . CLR allocates memory on heap and then copies the value type instance to it . Boxing is an a expensive process , science it copies an object from stack to a heap which requires a number of processor cycle as well space on the heap . Another advantage of using boxing is that the same object appears at two different place in memory .
 
                                        Unboxing  is an opposite of boxing . Instance of an object type interface created by boxing needs to be convert back into Unboxing .

for example :
using system;
using system.collections.generic;
using system.linq;
using system.Test;
{

int y;
object obj = y;   // boxing is implicit
int z ;
z = int(obj); // boxing
 }

Another exam[ple


for example :
using system;
using system.collections.generic;
using system.linq;
using system.Test;
{
class program
{
public static void Main(string [] args)
int a;
a=10;
object obj = a;    // boxing is implicit
a = (int) obj;        // unboxing
if ( obj is int);
{
console.WriteLine(" value is int type . .);
console.Readkey();
}
}
}

output       10
               value is int type . .

0 comments: