What is boxing in C#?


Boxing convert value type to an object type. Let us see an example of boxing −

int x = 50;
object ob = x; // boxing

In boxing, the value stored on the stack is copied to the object stored on heap memory, whereas unboxing is the opposite.

Boxing is useful in storing value types in the garbage-collected heap. It is implicit conversion of a value type to the type object.

Let us see an example −

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {

   static void Main() {
      int x = 50;
      object ob = x;

      x = 100;

      // The change in x won't affect the value of ob
      System.Console.WriteLine("Value Type = {0}", x);
      System.Console.WriteLine("Oject Type = {0}",ob);
   }
}

However, in Unboxing, the object's value stored on the heap memory is copied to the value type stored on stack. It has explicit conversion whereas boxing has implicit conversion.

Updated on: 21-Jun-2020

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements