Difference between Boxing and Unboxing in C#

Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enables a unified view of the type system in which a value of any type can be treated as an object.

Boxing Unboxing
It convert value type into an object type. It convert an object type into value type.
Boxing is an implicit conversion process. Unboxing is the explicit conversion process.
Here, the value stored on the stack copied to the object stored on the heap memory. Here, the object stored on the heap memory copied to the value stored on the stack .
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate Boxing
using System;
  
public class GFG {
    static public void Main()
    {
        int val = 2019;
  
        // Boxing
        object o = val;
  
        // Change the value of val
        val = 2000;
  
        Console.WriteLine("Value type of val is {0}", val);
        Console.WriteLine("Object type of val is {0}", o);
    }
}

chevron_right


Output:

Value type of val is 2000
Object type of val is 2019
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate Unboxing
using System;
  
public class GFG {
    static public void Main()
    {
        int val = 2019;
  
        // Boxing
        object o = val;
  
        // Unboxing
        int x = (int)o;
  
        Console.WriteLine("Value of o is {0}", o);
        Console.WriteLine("Value of x is {0}", x);
    }
}

chevron_right


Output:

Value of o is 2019
Value of x is 2019


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.