Boxing:
Boxing means conversion of a value type on the stack to a object type on the heap.When compiler finds a value type needs to convert in a reference type,it creates an object 'box'into that it places the value of value type.
Example:
int a=10;
Object b=a; //creates a box rm to hold m
a=20;
Here boxing create a copy of integer a to object b.Now both variables are different where the value of a resides on the stack and that of b on the stack.So,the values are independent of each other.
from above example value of a is 20 and that of b is 10.
Unboxing:
Its the process of converting the object type back to the value type.We can only unbox a variable that has previously been boxed.Its an explicit conversion because during unboxing the object can cast to any type.
Example:
int a=10;
object b=a; //boxing a implicitly
int c=(int)b; //unboxing explicitly
During unboxing,we have to ensure that the value type is large enough to hold the value of object.
No comments:
Post a Comment