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

Performance implications of boxing in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Boxing happens when a value type is converted to an object type. This can slow down your program because it uses extra memory and time.

When you need to store a number (like int) in a variable that holds objects.
When passing a value type to a method that expects an object.
When adding value types to collections that store objects, like ArrayList.
When you want to treat simple data like objects for flexibility.
Syntax
C Sharp (C#)
object obj = 123; // Boxing an int
int x = (int)obj; // Unboxing back to int

Boxing wraps a value type inside an object on the heap.

Unboxing extracts the value type from the object.

Examples
This example shows boxing an int into an object and then unboxing it back.
C Sharp (C#)
int number = 42;
object boxedNumber = number; // Boxing
int unboxedNumber = (int)boxedNumber; // Unboxing
Adding an int to ArrayList causes boxing because ArrayList stores objects.
C Sharp (C#)
ArrayList list = new ArrayList();
list.Add(10); // Boxing happens here
int value = (int)list[0]; // Unboxing
Sample Program

This program shows boxing and unboxing with a simple int and with an ArrayList. It prints the values before and after boxing.

C Sharp (C#)
using System;
using System.Collections;

class Program
{
    static void Main()
    {
        int a = 100;
        object b = a; // Boxing

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

        int c = (int)b; // Unboxing
        Console.WriteLine("Unboxed value: " + c);

        ArrayList list = new ArrayList();
        list.Add(200); // Boxing
        int d = (int)list[0]; // Unboxing
        Console.WriteLine("Value from ArrayList: " + d);
    }
}
OutputSuccess
Important Notes

Boxing creates a copy of the value on the heap, which uses more memory.

Unboxing requires a cast and can throw an error if the object is not the correct type.

Frequent boxing and unboxing can slow down your program, so avoid it when possible.

Summary

Boxing converts value types to objects and uses extra memory and time.

Unboxing converts objects back to value types and requires a cast.

Minimize boxing to keep your program fast and efficient.