Thursday 20 November 2014

Boxing & UnBoxing In C#

C# is a strongly-typed language. Every variable and constant has a type, as does every expression that evaluates to a value. In this article I will share about understanding Boxing and UnBoxing in C#.
C# Type System contains three Types , they are Value Types , Reference Types and Pointer Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation
is called Unboxing.
Boxing:
Example
1: int akm = 1;
2: Object Obj = akm; //Boxing
The first line we created a Value Type akm and assigned a value to akm. The second line , we created an instance of Object Obj and assign the value of akm to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.
UnBoxing
Example
1:Int akm=1;
2:Object Obj=akm; //Boxing
3:Int i=(int)Obj; //Unboxing
The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.
Difference Between Boxing & UnBoxing

Boxing
Unboxing
Definition:
Boxing is the process of converting a value type to the reference type.
Unboxing is the process of converting a reference type to value type
.
Type of Conversion:
Implicit Conversion
Explicit Conversion

Example:
int akm = 221;
object obj = akm; //boxing
object obj = 213;
akm = (int)obj ; // unboxing



0 comments::

Post a Comment

Copyright © DotNet-Ashok