What is boxing and unboxing in C#? Difference and example.

Boxing: Converting value type (int, float,char) to reference type (System.Object). In C# any type can be treated as an object.

Unboxing : extracts the value type from the object .

BOXINGUNBOXING
Converts value type to object.Converts an object to value type.
Implicit conversion. object obj = 123;Explicit conversion. Casting required int i = (int)obj;
objects are stored on heap.value type are stored on stack
Boxing is safe.InvalidCastException on incorrect casting.
NullReferenceException if value is null.

Drawback: Boxing and unboxing both are expensive operation hence should be used only if necessary.

Example: ArrayList is a built-in data structure in C# which stores elements as an object.

In the above example each item in the ArrayList is stored as an object hence boxing is performed. To extract values back from the object unboxing needs to be done.