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 type object. Boxing and unboxing enables 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 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 object, int values are simply 32 bit values. For programs that need int's 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 System.Object in the .NET Framework.

The example

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

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

The 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 object and back again to int. This example shows both boxing and unboxing.

Up Next
    Ebook Download
    View all
    Learn
    View all