Boxing and Unboxing in C#

 

boxing-unboxing-in-csharp-dotnetkida


Boxing is the conversion of a value type (stack) to a Object type (heap).

Boxing is implicit.


In the following example, the integer variable a is boxed and assigned to object b.

Example:

int a = 2020; // The following line boxes a. object b = a;
 

Unboxing is the conversion of a Object type back to a Value type. 
Unboxing is explicit. We have to cast explicitly.


int a = 2020; // a value type

object b = a; // boxing
int c = (int)b; // unboxing


When boxing a value, we have to ensure that the value type is large enough to hold the value of the object.


Post a Comment

0 Comments