Introduction
In this blog, I will explain boxing and unboxing in C#, which introduces two methods. Boxing and unboxing are both conversion types. Boxing is implicitly conversion and unboxing is explicitly a conversion type. The basic difference between boxing and unboxing is that boxing is the conversion of the value type to an object type, whereas unboxing refers to the conversion of the object type to value type.
Boxing
- Boxing refers to the conversion of the value type to object type.
- It is implicitly conversion.
- The value is stored on the stack memory and copied to the object stored on heap memory.
Example
- public class Sample
- {
- static void Main()
- {
- int i = 20;
- object obj = i;
- }
-
- }
Unboxing
- Unboxing refers to the conversion of the object type to value type.
- It is explicitly conversion.
- The object value stored on the heap memory is copied to the value type stored on stack memory.
Example
- public class Sample
- {
- static void Main()
- {
- object obj = 20;
- int i = (int)obj;
- }
-
- }