Difference between Boxing and Unboxing in C#

Boxing and Unboxing: Boxing is the process of converting a value type into a reference type, and unboxing is the process of converting a reference type back into a value type.

c-sharp-boxing-unboxing
C# Boxing & Unboxing

Understanding boxing and unboxing in c#

Let’s learn more about boxing and unboxing in C# programming with some sample code examples.

Sr.No.Boxing In C#UnBoxing In C#
1.Boxing is the process of converting a Value Type variable (char, int, float, double, etc) into a Reference Type variable (such as an object or any interface type).Unboxing is the opposite of boxing. It is the process of converting a reference type to a value type. Unboxing extracts a value from a reference type (object) and assigns it to a value type.
2.Boxing is an implicit conversion process of a value type to the Object (base type).Unboxing is an explicit conversion process.
3.The value on the stack is copied to the object on the heap memoryUnboxing explicitly cast the object or interface type to the value type.
4.Value Type variables are stored in Stack memory, while Reference Type variables are stored in Heap memory.During unboxing, the boxed value type is unboxed from the heap and assigned to the value type allocated on the stack.
5.Example:
In the example below, the integer variable i is boxed and assigned to the object o.

int i = 10;
// The following line boxes variable i.
object o = i;
Example:
Here, you can Unbox the object o and assign it to the integer variable j.

int i = 10; // a value type
object o = i; // boxing
int j = (int)o; // unboxing
Differences between boxing and Unboxing In C#

The concept of boxing and unboxing is the core of the type system in C# programming. It creates a bridge between value types and reference types by allowing any value of a value type to be converted to and from an object type.

The following figure demonstrates the boxing & Unboxing:

boxing-unboxing-conversion-operation
Boxing & Unboxing conversion.

Example: Boxing

A boxing conversion creates a copy of a value. Therefore, changing the value of one variable does not affect the other variables.

A C# program to demonstrate boxing is as follows:

using System;
public class BoxingExample
{
    public static void Main(string[] args)
    {
        int num = 100;  
        object obj = num;  // Boxing

        Console.WriteLine($"obj = {obj}"); // Output: obj = 100

        // Change the value of obj
        obj = 101;

        Console.WriteLine($"num ={num}, obj= {obj}");//Output: num =100, obj= 101
        Console.ReadLine();
    }
}

Example: UnBoxing

A C# program to demonstrate Unboxing is as follows:

using System;
public class UnBoxingExample
{
    public static void Main(string[] args)
    {
        int num = 100;  
        object obj = num;  // Boxing
       
        int x = (int)obj;  // Unboxing
        Console.WriteLine($"obj = {obj} , x = {x}");//Output: obj = 100 , x = 100
        Console.ReadLine();
    }
}

Code Explanation: In the above lines of code, we have created a variable of type integer (value type) num and assigned it the value 100. Here we box the num variable into a reference type variable obj of type object. The value from obj will then be unboxed into a new integer variable x.

Note: An InvaidCastException will be thrown if the value type does not match the boxed object, as shown in the following example.

Unboxing-InvaidCastException-example
Unboxing-InvaidCastException-example

In the above example, the obj points to a boxed object of type int, but we are trying to unbox it to type double rather than int. That’s why the compiler throws   InvalidCastException .

C# Boxing ConversionsC# Unboxing Conversions
Boxing conversions allow implicit conversions from value type to reference type. The following box conversions exist in C#:An unboxing conversion lets you explicitly convert a reference type to a value type.
The unboxing conversions are:
1. Conversion from any value type to the object type.Conversion from the object type to any value type.
2. Conversion from any value type to the type System.ValueTypeFrom the type System.ValueType to any value type.
3. From any non-nullable value type to any interface type implemented by the value type.From any interface type to any non-nullable value type that implements the interface type.
4. From any nullable type to any interface type implemented by the underlying type of the
nullable type.
From any interface type to any nullable type whose underlying type implements the
interface type.
5. From any enum type to the type System.EnumFrom the type System.Enum to any enum type.
Boxing vs Unboxing Conversion

Q: What are the disadvantages of boxing?

Ans: The drawbacks of boxing include the following:
1. Boxing is an expensive procedure since it copies an item from a stack to the heap, which requires extra memory space and steps to perform it.
2. The same object appears twice in a different memory location, which can have contradictory states.

Q: Which is the implicit conversion, Boxing or Unboxing?

Ans: Boxing is the process of implicit conversion of a value type into a reference type.

Q: How do generics prevent boxing?

Ans: When you use a Generic List<T>, It allows only elements of a specified type. The compiler generates a special code for that value type and keeps the actual values in the list rather than a reference to an object that contains the values. So no boxing is required.

Q: Why do we need boxing In C#?

Ans: Boxing is required when we have a function that takes an object as a parameter, but we have different value types that need to be passed, and you can’t know the type of a value at compile time.

Q: What is the difference between boxing and unboxing in C# .NET?

The basic difference between boxing and unboxing is that boxing is a conversion from a value type to an object type, whereas the term unboxing refers to the conversion from an object type to a value type.

Conclusion:

This article has covered the “boxing and unboxing” of variables. We discussed examples of each and examined the results of each process.
It`s also important to note that boxing and unboxing variables require a lot of memory space. When a variable is boxed, a new memory block and object are created. It is advised against using these techniques frequently because continuously boxing and unboxing variables can significantly degrade performance.

References: MSDN-Boxing and Unboxing, “The C# Programming Language” by Anders Hejlsberg

I sincerely hope you enjoyed reading “Boxing and Unboxing“. If you would like to provide more details on the topic covered here. Please leave a comment below.

Articles to Check Out:

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Lucas
Lucas
7 months ago

The post is clearly written and interesting. Appreciate your excellent work.👍