Learn what Boxing is in C# and how to perform it correctly.
Boxing is the process of converting a value type to a reference type. This involves wrapping a value type (like int, float, char) in an object or any interface type implemented by this value type.
using System;
class Program
{
  static void Main()
  {
    int valType = 10;
    object objType = valType; // Boxing
    Console.WriteLine("Value Type: " + valType);
    Console.WriteLine("Object Type: " + objType);
  }
}
Value Type: 10 Object Type: 10
The output demonstrates the Boxing process where valType, an integer (value type), is boxed into objType (object type). Both display the same value, but objType is a reference type stored in the heap.
Boxing is a fundamental concept in C#, allowing value types to be treated as objects. While it is necessary in certain scenarios, developers should be aware of its performance implications.
50 comments