Monday, February 19, 2024

boxing and unboxing

In C#, boxing and unboxing are concepts related to converting value types (such as int, char, etc.) to reference types (such as object). Let’s explore both concepts with examples:

  1. Boxing:

    • Boxing is the process of converting a value type to the type object or any interface type implemented by that value type.
    • When the Common Language Runtime (CLR) boxes a value type, it wraps the value inside an object instance and stores it on the managed heap.
    • Here’s an example of boxing:
      int i = 123; // The following line boxes 'i'.
      object o = i;
      
    • In this example, the integer variable i is boxed and assigned to the object variable o.
  2. Unboxing:

    • Unboxing is the process of extracting the value type from an object.
    • It converts the object back to its original value type.
    • Example of unboxing:
      o = 123; // Unboxing: extract the value from 'o' and assign it to 'i'.
      int unboxedValue = (int)o;
      
  3. Practical Example:

    • Let’s create a heterogeneous collection using an ArrayList (a dynamically sized array of objects):
      ArrayList mixedList = new ArrayList();
      mixedList.Add("First Group:"); // Add a string element
      for (int j = 1; j < 5; j++)
      {
          mixedList.Add(j); // Add integers (boxing occurs)
      }
      mixedList.Add("Second Group:");
      for (int j = 5; j < 10; j++)
      {
          mixedList.Add(j);
      }
      
      // Display the elements in the list
      foreach (var item in mixedList)
      {
          Console.WriteLine(item);
      }
      
      // Calculate the sum of squares of the first group of integers
      var sum = 0;
      for (var j = 1; j < 5; j++)
      {
          sum += (int)mixedList[j] * (int)mixedList[j]; // Unboxing
      }
      Console.WriteLine($"Sum: {sum}"); // Output: Sum: 30
      
    • In this example, we box integers when adding them to the ArrayList and unbox them during the sum calculation.

Remember that boxing and unboxing have performance implications, so use them judiciously.