This example shows you How to use Boxing and Unboxing in C# Programming.

C# Boxing and Unboxing

C# has three data types, such as:

  • Value Types
  • Reference Types
  • Pointer Types

You can easily convert a Value Type to a Reference Type, and back again to Value Type.

Boxing

Allows you to convert from Value Type to Reference Type.

int value  = 12;
Object obj = value;//boxing

Unboxing

Allows you to convert from Reference Type to Value Type.

int value = 12;
Object obj = value;//Boxing
int x = (int)obj;//Unboxing

This time we will create the first console application to run our code.

using System;

namespace ConsoleAppExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int value = 12;
            Object obj = value;//Boxing
            int x = (int)obj;//Unboxing
            Console.WriteLine("{0}", x);
            Console.ReadLine();
        }
    }
}

Through the above example, I hope you understand Boxing and Unboxing in c# programming.