vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Wednesday, January 2, 2013

Boxing and UnBoxing in C#.Net and VB.NET


In Dot net they are two type of data types, namely Value type and Reference type. Already I have discuss these data types in an article for more refer the below link
http://www.dotnetcode.in/2012/12/data-types-in-c.html

Boxing:
The conversion of value type to reference type is known as Boxing. That means conversion of value type on stack to an object type on the heap.
Boxing is an implicit conversion type.
E.g.
C#
int m=50; (Value type)
object n; (Reference type)
n=m;
When we run the above code the compiler automatically convert m into reference type and place the value 50 in object n.
Vb.Net
Dim j as integer=50
Dim m as object =j
UnBoxing:
The conversion of reference type to value type is known as UnBoxing. That means conversion of reference type on heap to value type on stack.
But in unboxing the conversion takes place explicit operation using C-Type casting
E.g.
C#
Object m=10; (Refernce type)
Int n; (value type)
n=(int) m;
When unboxing a value, we must ensure that value type is large enough to hold the reference values otherwise it throw a runtime error for an example refers the below code...
object m=700;
byte n=(byte) m;
When you run the above code it will produce run time error, reason that byte type is not enough to hold the reference value.
Vb.Net
Dim m as object=10
Dim i as integer
i=ctype(m,integer)
I hope it helps. Post  your comments here

0 comments:

Post a Comment