Articles → CSHARP → Boxing And Unboxing In C#

Boxing And Unboxing In C#






Boxing





Unboxing





Example




using System;

namespace BoxingUnboxingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int intValue = 42;
            object boxedValue = intValue; // Boxing

            Console.WriteLine($"Original value: {intValue}");
            Console.WriteLine($"Boxed value: {boxedValue}");

            // Unboxing: Converting reference type back to value type
            int unboxedValue = (int)boxedValue; // Unboxing

            Console.WriteLine($"Unboxed value: {unboxedValue}");

            Console.ReadLine();
        }
    }
}



Output


Picture showing the output of boxing and unboxing in C#
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Sunday, May 10, 2015

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250