0
0
C Sharp (C#)programming~5 mins

Boxing and unboxing execution in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Boxing and unboxing let you convert between simple values and objects so you can use them in different ways.

When you want to store a simple value like an int inside an object variable.
When you need to pass a value type to a method that expects an object.
When you want to retrieve the original value from an object after storing it.
When working with collections that store objects but you want to use value types.
When you want to treat value types as objects temporarily.
Syntax
C Sharp (C#)
int number = 123;          // value type
object obj = number;         // boxing
int original = (int)obj;     // unboxing

Boxing wraps a value type inside an object.

Unboxing extracts the value type back from the object and requires a cast.

Examples
Boxing stores the int in an object, unboxing retrieves it back.
C Sharp (C#)
int x = 10;
object o = x;  // boxing
int y = (int)o;  // unboxing
Boxing and unboxing also work with other value types like double.
C Sharp (C#)
double d = 3.14;
object obj = d;  // boxing
double val = (double)obj;  // unboxing
Boxing and unboxing work with bool values too.
C Sharp (C#)
bool flag = true;
object boxedFlag = flag;  // boxing
bool unboxedFlag = (bool)boxedFlag;  // unboxing
Sample Program

This program shows boxing by storing an int inside an object, then unboxing it back to int.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int number = 42;           // value type
        object boxedNumber = number;  // boxing

        Console.WriteLine("Boxed value: " + boxedNumber);

        int unboxedNumber = (int)boxedNumber;  // unboxing
        Console.WriteLine($"Unboxed value: {unboxedNumber}");
    }
}
OutputSuccess
Important Notes

Boxing creates a new object on the heap, so it uses more memory and time than using value types directly.

Unboxing requires an explicit cast and will throw an error if the object does not contain the correct value type.

Try to minimize boxing/unboxing in performance-critical code.

Summary

Boxing converts a value type to an object.

Unboxing converts the object back to the original value type.

Boxing and unboxing let you use value types where objects are needed.