Explain the uses of boxing and unboxing.
Boxing and Unboxing are used to convert value types into reference types and vice versa. Developers often need to make some methods generic and hence create methods that accept objects rather than specific value types. The advantage of reference types is that they don’t create a copy of the object in memory, instead pass the reference of the data in the memory. This uses memory much more efficiently, especially, if the object to be passed is very heavy.
public class MyClass
{
public void MyClass()
{
}
public void MyMethod()
{
int intVar1 = 1; // i is an integer. It is a value type variable.
object objectVar = intVar1;
// boxing occurs. The integer type is parsed to object type
int intVar2 = (int)objectVar;
// unboxing. The object type is unboxed to the value type
}
}