There are two categories of data types in .Net, those are Value type and Reference type. Sometimes we have requirement like storing value type variable like reference type variable. We can store value type variables in reference type by using technique called Boxing and we can get back the Value type variable by using technique called Unboxing in C#.
By using Boxing in C# we can explicitly convert value type into a corresponding reference type by storing the variable in a System.Object. After Boxing a value, the CLR allocates a new object on the heap and copies the value types into that instance. What is returned to you is a reference to the newly allocated object. By using this technique, we can temporarily treat stack data as heap-allocated objects.
using System;
namespace BoxingInCSharp
{
class Program
{
static void Main(string[] args)
{
int i;
i = 100;
//boxing technique in C#
object obj = i;
//unboxing the reference type back into int variable
int j = (int)obj;
}
}
}
As shown above we converted the int Value type to reference type(here Object type). Unboxing is the process of converting the value held in the object reference back into a corresponding value type on the stack, here int type.