Day 23 : Boxing and Unboxing
In this blog we are going to understand the concept of boxing and unboxing.
Boxing :
- Boxing is the process of converting a value-type to a reference-type.
- When CLR(Common Language Runtime) boxes a value-type, it wraps a value inside System.Object instance and stores it on managed heap.
- In simple words, Boxing is used to store the value type in the garbage collected heap.
- Boxing is an implicit conversion of value type to object.
- Example :
In above example, 'a' is a int(value-type) have value '200'. After that object 'o' copies value from 'i' i.e boxing. The result of this statement is, it creates object reference 'o' on stack and that references value of type int('i') on heap.
- We can also perform explicit boxing but it is not required.
- Example :
object o=(object)i; //explicit boxing
- Boxing always makes a copy of value. So, changing value of one variable will not affect other as shown in above example.
- The casting of boxed value is not permitted.
Unboxing :
- Unboxing is the process of converting a reference-type to a value-type.
- Unboxing is an explicit conversion of object to value type.
- We can also say that, Unboxing is the process of retrieving value from boxed object.
- The unboxing operation consists of :
- Checking object instance to make sure that it is boxed value.
- Copying value from instance into value-type variable.
- Example :
In above example, 'a' is a int(value-type) have value '50'. After that object 'o' copies value from 'i' i.e boxing. The result of this statement is, it creates object reference 'o' on stack and that references value of type int('i') on heap. After that int 'b' copies value from object 'o' i.e unboxing. The result of this statement is, it copies value from heap and store it on stack (into value-type 'b').
"For unboxing an item, the item referencing to an object that must be firstly boxed by value-type."
Conclusion :
- Boxing and Unboxing degrade the performance so developers always avoid using it. We can use generics to avoid this.
- Boxing and Unboxing consume more memory and time.
- Both increases overhead and lacks in safety measures.
Thank You!!!
For more understanding watch below video :
Comments
Post a Comment