# C# : Boxing and Unboxing

While working with C# datatypes, developers often needs to convert `value` types to `reference` type or vice-versa. The process of converting `value` type to `reference` type is termed as **boxing** and converting a `reference` type to `value` type is termed as **unboxing.**

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">A value type variable is immutable data which contains the data, instead of a reference to it. Value types often have short lives. They are typically stored in memory in an area known as the stack. The stack is where data that does not need to exist for long lives. Structs, Int32, DateTime, and Double are examples of value types.</div>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>A reference type variable contains a reference to data stored in memory, also known as the heap</strong>. The heap is most often used for data that has a longer life. You can have more than one variable point to the same referenced data. Objects are an example of a reference type</div>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">In C#, <code>System.Object</code> is parent class of all the types, it means its possible to assign in any value to <code>Object</code> type instance. [Object = an alias of <code>System.Object</code> ]</div>
</div>

### Boxing

Boxing is the process of converting `value` type (int, char etc) to `reference` type (object). Boxing is an implicit conversion where a `value` type being allocated on the heap rather than the stack.

```csharp
int i = 10;
object o = i; //performs boxing - implicit boxing
object o = (object)i;  // explicit boxing
object o = (object)i;  // explicit boxing but never required

//more practical example
List<object> mixedList = new List<object>();

mixedList.Add("First Group:");  // boxing - string to object
mixedList.Add(10);              // boxing - int to object
```

### Unboxing

Unboxing is explicit conversion from Object / reference type to value type. In the unboxing process, the boxed value type is unboxed from the heap and assigned to a value type that is stored on the stack. This process involves below steps

* Checking that object instance being 'unboxed' is a 'boxed' value of given value type.
    
* copying the value from object instance to value-type variable.
    

```csharp
int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

//more practical example
List<object> mixedList = new List<object>();

mixedList.Add("First Group:");  // boxing - string to object
mixedList.Add(10); 
foreach (var item in mixedList) {
    // mixedList items are of object type,
    // while priting, object type will be 'unboxed' to 
    // corresponding value-type.
    Console.WriteLine(item); 
}
```

> For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox `null` causes a [NullReferenceException](https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception). Attempting to unbox a reference to an incompatible value type causes an [InvalidCastException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception).

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Boxing and unboxing are expensive process computationally, so they must be used only when necessary.</div>
</div>

That's it for this article. Thanks for reading it and share your thoughts in comment section.

### References and further reading

* [https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing)
    
* [https://www.pluralsight.com/guides/csharp-passing-reference-vs-value-objective](https://www.pluralsight.com/guides/csharp-passing-reference-vs-value-objective)
