đ In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to an object, itâs called boxing. When a variable of type object is converted to a value type, itâs called unboxing.
đ„Â More simply, when declaring the basic data types, the value is stored on the Stack and Boxing memory is the transfer from the Stack to the Heap.
Boxing In C#
Example Boxing:
int num = 123; // 123 will be assigned to num (Stack)
Object Obj = num; // Boxing (Move Stack to Heap)
Unboxing In C#
Example Unboxing:
int num = 23; // value type is int and assigned value 23
Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing - casting