Is There Any Need To Boxing And Unboxing

Introduction

With Boxing and unboxing, one can link between value types and reference types by allowing any value of a value type to be converted to and from a type object. Boxing and unboxing enable a unified view of the type system wherein a value of any type can ultimately be treated as an object.

Converting a value type to a reference type is called Boxing. Unboxing is an explicit operation. In this article, let us see would we really need to box a data type.

The type system unification provides value types with the benefits of object-ness and does so without introducing unnecessary overhead. For programs that don't need int values to act like objects, int values are simply 32-bit values. For programs that need ints to behave like objects, this functionality is available on-demand. This ability to treat value types as objects bridges the gap between value types and reference types that exists in most languages. All types in C# - value and reference inherit from the Object superclass. The object type is based on the System. Object in the .NET Framework.

Example

using System;
class Test
{
    static void Main()
    {
        Console.WriteLine(3.ToString());
    }
}

calls the object-defined ToString method on an integer literal.

Example

class Test
{
    static void Main()
    {
        int i = 123;
        object o = i; // boxing
        int j = (int)o; // unboxing
    }
}

is more interesting. An int value can be converted to an object and back again to int. This example shows both boxing and unboxing.

Up Next
    Ebook Download
    View all
    Learn
    View all