Boxing & Unboxing in .NET
When we declare a variable in .NET application, some memory gets allocated to it. This memory has 3 parts: Name, Datatype & Value of the variable. The datatype of our variable decides the memory allocation to be made either in Heap or Stack. But before moving ahead, let’s have a quick looks at Value Type and Reference Type variables.
Value Type variable is the one that holds both data and memory in same location i.e. on stack. whereas Reference Type just hold a reference pointer in the stack which points to a memory location on the heap. Now we have basic understanding of value type and reference type so let’s have a quick look at what is boxing & unboxing and how it creates a performance hit.
Boxing is when a value type is converted to reference type and unboxing is when a reference type gets move to a value type variable. But when a value type is boxed a memory allocation is made on heap to store the value type as an object. This allocation and subsequent garbage collection introduces serious performance issues in performance-critical scenarios. Similarly unboxing involves checking of boxed object type before extracting it’s value and this type checking adds additional runtime overhead, especially if it happens frequently. Code snippet is attached for further understanding.
#region Boxing & Unboxing
int i = 1;
object obj = i; // Boxing
int j= (int)obj; //UnBoxing
#endregion