In this article I will explain what is boxing and unboxing in C#.
Boxing in C# is a process of converting a value type into object type.
Unboxing is a process of converting an object type into a value type.
Example:
using System;
public class Program
{
public static void Main()
{
int i = 1;
object boxed = (object) i;
int unboxed = (int) boxed;
}
}
Firstly, we define a new integer variable i with the value of 1.Then we are projecting the value i into object type and storing the result in the boxed variable. This is how the boxing looks like.
After that, we can project the boxed variable into integer to perform the unboxing.
Boxing was very important in the past, when we were using for example ArrayLists instead of generic collections. ArrayList has a method called Add which takes an object as a parameter. Without boxing, we wouldn't be able to use this method using an integer.
ArrayList arrayList = new ArrayList();
arrayList.Add(i);