welcome Netizen

welcome Netizen
Hi folks this site Share Basic Knowledge in .NET, DotNet, C#,DOT NET CODE, ASP.NET, VB.NET, DOT NET TRICKS,Dotnetcode,Android and Latest Technology Articles in VB,Android and ASP.NET

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

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.
int m=50; (Value type)
object n; (Reference type)
When we run the above code the compiler automatically convert m into reference type and place the value 50 in object n.
Dim j as integer=50
Dim m as object =j
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
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.
Dim m as object=10
Dim i as integer
I hope it helps. Post  your comments here


Post a Comment