Open In App

C# | Boxing And Unboxing

Prerequisite : Data Types in C#

Boxing and unboxing are important concepts in C#. The C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, Boxing converts a Value Type variable into a Reference Type variable, and Unboxing achieves the vice-versa. Boxing and Unboxing enable a unified view of the type system in which a value of any type can be treated as an object.

Boxing In C#



int num = 23; // 23 will assigned to num
Object Obj = num; // Boxing

Boxing




// C# implementation to demonstrate
// the Boxing
using System;
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // assigned int value
        // 2020 to num
        int num = 2020;
 
        // boxing
        object obj = num;
 
        // value of num to be change
        num = 100;
 
        System.Console.WriteLine
        ("Value - type value of num is : {0}", num);
        System.Console.WriteLine
        ("Object - type value of obj is : {0}", obj);
    }
}

Output:
Value - type value of num is : 100
Object - type value of obj is : 2020

Unboxing In C#



int num = 23;         // value type is int and assigned value 23
Object Obj = num;    // Boxing
int i = (int)Obj;    // Unboxing

Unboxing




// C# implementation to demonstrate
// the Unboxing
using System;
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // assigned int value
        // 23 to num
        int num = 23;
 
        // boxing
        object obj = num;
 
        // unboxing
        int i = (int)obj;
 
        // Display result
        Console.WriteLine("Value of ob object is : " + obj);
        Console.WriteLine("Value of i is : " + i);
    }
}

Output:
Value of ob object is : 23
Value of i is : 23

Article Tags :
C#