Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding Boxing and Unboxing in C#

Understanding Boxing and Unboxing in C#

13 Sep 2024
Intermediate
200K Views
7 min read
Learn with an interactive course and practical hands-on labs

Best Free C# Course: Learn C# In 21 Days

Boxing and Unboxing: An Overview

Boxing and unboxing are the most important concepts you always get asked in your interviews. Actually, it's really easy to understand and simply refers to the allocation of a value type (e.g. int, char, etc.) on the heap rather than the stack.

While working with data types such as strings, objects, and arrays, we often need to convert the value types to the reference types or vice-versa. Because both have different characteristics and .NET stores them differently in the memory location, This must be required to do some work or define some settings that work internally to convert them from one data type to another. These conversion processes are generally called as a terms boxing and unboxing. In this C# Tutorial, We will explore about boxing and unboxing which includes, What is boxing in C#, What is unboxing in C#, Difference between boxing and unboxing in C#.

Boxing and Unboxing

What is Boxing?

  • Implicit conversion of a value type (int, char, etc.) to a reference type (object), is known as Boxing.
  • In the boxing process, a value type is allocated on the heap rather than the stack.
  • A boxing conversion is intended for creating a copy of the value being boxed. This type of conversion is completely different from a conversion of a reference type to a type object, in which the value that is being converted continues to reference the same instance and simply is regarded as the less derived type object.

Syntax

Declare one variable with its value

 int z = 222;

boxing operation

 object x= z;

Here Boxing copies the value of z into object x. Let's elaborate on this in C# Compiler

Example of Boxing

 class TestBoxing
{
    static void Main()
    {
        int z = 222;

       
        object x = z;

        z = 444;

        System.Console.WriteLine("The value-type value = {0}", z);
        System.Console.WriteLine("The object-type value = {0}", x);
    }
}

Output


The value-type value = 444.The object-type value=222
  

Explanation

At first, we initialized one variable"z" along with its value. Then we did a boxing operation and assigned that variable to one object. After that, we gave another value to "z".But because of boxing, the change in "z" doesn't affect the value stored in x.

What is Unboxing?

  • Explicit conversion of the same reference type (which is being created by the boxing process)
  • back to a value type is known as unboxing.
  • In the unboxing process, the boxed value type is unboxed from the heap and assigned to a value type that is being allocated on the stack.
  • In other words, The unboxing conversion is a completely reversed process of boxing that we have seen already.
  • Unboxing is the process of converting a reference data type to a value type such as a string or integer. The unboxing conversion extracts the value from the reference type and assigns it to a value type.

Syntax

 // int (value type) is created on the Stack
int stackVar = 12; 

// Boxing = int is created on the Heap (reference type)
object boxedVar = stackVar; 

// Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
int unBoxed = (int)boxedVar;  

Example of Unboxing

 int i = 10;
ArrayList arrlst = new ArrayList();

//ArrayList contains object type value
//So, int i is being created on heap
arrlst.Add(i); // Boxing occurs automatically

int j = (int)arrlst[0]; // Unboxing occurs

Note

  1. Sometimes boxing is necessary, but you should avoid it if possible since it will slow down the performance and increase memory requirements.

    For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and requires extra memory (around twice the memory of the original value type).

  2. Attempting to unbox a null causes a NullReferenceException.

     int? stackVar = null;
    // Boxing= Integer is created on the Heap
    object boxedVar = stackVar;
    
    // NullReferenceException
    int unBoxed = (int)boxedVar; //Object reference not set to an instance of an object.
       
  3. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

     
    int stackVar = 12;
    // Boxing= Integer is created on the Heap
    object boxedVar = stackVar;
    
    // InvalidCastException
    float unBoxed = (float)boxedVar; //Specified cast is not valid.
    

Difference Between Boxing and Unboxing in C#

Difference Between Boxing and Unboxing in C#
Conclusion:

The boxing and unboxing type system unification provides the value types with the benefits of object characteristics without introducing the unnecessary overhead of the type conversions. I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Also, consider our C# Programming Course for a better understanding of C# concepts.

FAQs

Boxing is the process of converting a primitive datatype into an object wrapper datatype, and unboxing is the process of converting a value from an object wrapper type back to the native primitive value. 

Unboxing you are emptying everything everything inside the box. In boxing you are taking everything outside the box and putting it in the box

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type

Take our Cpp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this