Boxing vs UnBoxing in .NET

Posted by

Boxing and unboxing are two important concepts in . NET.

Boxing: Boxing is the process of converting a value type to an object type. When you box a value type, a new object is created on the managed heap to hold the value, and the value is stored in that object. Boxing is often used when you need to pass a value type to a method that takes an object type as a parameter, or when you need to store value types in a data structure, such as an ArrayList, that is designed to hold objects.

Unboxing: Unboxing is the opposite of boxing. It is the process of extracting a value from an object that was previously boxed. An unboxing operation requires a cast to be performed to convert the object back to a value type. The cast operation checks that the object is actually an instance of the correct value type, and if the cast is successful, the value is extracted from the object and stored in a value type variable. If the cast is not successful, an InvalidCastException is thrown.

Example:

int i = 123;
object o = i; // boxing
int j = (int)o; // unboxing

In this example, the value of i is boxed and stored in the object o. Then, o is unboxed and the value is stored in j.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.