
While working with C# datatypes, developers often needs to convert value types to reference type or vice-versa. The process of converting value type to reference type is termed as boxing and converting a reference type to value type is termed as unboxing.
System.Object is parent class of all the types, it means its possible to assign in any value to Object type instance. [Object = an alias of System.Object ]Boxing
Boxing is the process of converting value type (int, char etc) to reference type (object). Boxing is an implicit conversion where a value type being allocated on the heap rather than the stack.
int i = 10;
object o = i; //performs boxing - implicit boxing
object o = (object)i; // explicit boxing
object o = (object)i; // explicit boxing but never required
//more practical example
List<object> mixedList = new List<object>();
mixedList.Add("First Group:"); // boxing - string to object
mixedList.Add(10); // boxing - int to object
Unboxing
Unboxing is explicit conversion from Object / reference type to value type. In the unboxing process, the boxed value type is unboxed from the heap and assigned to a value type that is stored on the stack. This process involves below steps
Checking that object instance being 'unboxed' is a 'boxed' value of given value type.
copying the value from object instance to value-type variable.
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing
//more practical example
List<object> mixedList = new List<object>();
mixedList.Add("First Group:"); // boxing - string to object
mixedList.Add(10);
foreach (var item in mixedList) {
// mixedList items are of object type,
// while priting, object type will be 'unboxed' to
// corresponding value-type.
Console.WriteLine(item);
}
For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox
nullcauses a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
That's it for this article. Thanks for reading it and share your thoughts in comment section.
References and further reading
Comments
Join the discussionNo comments yet. Be the first to comment.
