Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.
Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.
Example:
Boxing – Converting a value type to reference type is called boxing. An example is shown below.
1 2 3 4 |
int i = 120; object obj = (object)i; // Boxing |
Unboxing – Converting a reference type to a value typpe is called unboxing. An example is shown below.
1 2 3 4 |
obj = 120; i = (int)obj; // Unboxing |
Example(Structure):
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Program { static void Main(string[] args) { Point p = new Point(10, 10); object box = p; p.x = 20; Console.WriteLine(((Point)box).x); //10 Console.WriteLine(p.x); //20 Console.ReadLine(); } struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } } |
Example(Class):
Will output the value same on the console because the implicit boxing operation that occurs in the assignment of p2 to box causes the value of p to be copied. If had Person instead been declared a class, the value same would be output because p and box would reference the same instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Person { public string Name; public string Surname; public Person(string name,string surname) { Name = name; Surname = surname; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Program { static void Main(string[] args) { Person p1 = new Person("Ilye", "Mike"); object p2 = p1; p1.Name = "Michael"; Console.WriteLine("Person 1 Name:{0}",p1.Name); Console.WriteLine("Person 2 Name:{0}",((Person)p2).Name); Console.ReadLine(); } } |