Boxing And Unboxing in C#
There are we are going to learn about Boxing and Unboxing.
Introduction
In object-oriented programming , method are invoked using objects. since value type such as int and long are not object, we cannot use them to call methods. C# enables us to achieve this through a technique know as boxing. Boxing means the conversion of a value type on the stack to a object type. and voice-versa is unboxing.
Boxing
Any type , value or reference can be assigned to an object without an explicit conversion. When the compiler finds a value type where it need a reference type, it creates an object box into which it places the value of the value type.
Unboxing
Unboxing is the process of converting the object into value type.
Example:
int i = 123;
object o = (object)i; // boxing
Console.WriteLine("value of o object:-"+i);
o = 323;
i = (int)o; //unboxing
Console.WriteLine("value of i:- "+o);
Console.ReadLine();
Output