Interview Question
Qus: What do you know about boxing and unboxing?
Answers (2)
Implicit
Converting a value type to the type object
eg : obj myObject = i;
Unboxing
Explicit
Extracting the value type from the object
eg : i = (int)myObject;
Example: Boxing Copy
int i = 10;
object o = i; //performs boxing
In the above example, the integer variable i is assigned to object o. Since object type is a reference type and base class of all the classes in C#, an int can be assigned to an object type. This process of converting int to object is called boxing.
Unboxing - It is the reverse of boxing. It is the process of converting a reference type to value type. Unboxing extract the value from the reference type and assign it to a value type.
Unboxing is explicit. It means we have to cast explicitly.
Example: Unboxing Copy
object o = 10;
int i = (int)o; //performs unboxing