C# Boxing and Unboxing Needed


With Boxing and unboxing one can link betweenvalue-types and reference-types by allowing any value of a value-typeto be converted to and from type object. Boxing and unboxing enables aunified view of the type system wherein a value of any type canultimately be treated as an object.Converting a value type to reference type is called Boxing.Unboxing isan explicit operation.In this article let us see would we really needto box a data type?

The type system unification provides valuetypes with the benefits of object-ness, and does so without introducingunnecessary overhead. For programs that don't need int values to actlike object, int values are simply 32 bit values. For programs thatneed int's to behave like objects,this functionality is available on-demand. This ability to treat valuetypes as objects bridges the gap between value types and referencetypes that exists in most languages.

All types in C# – value and reference inheritfrom the Object superclass. The object type is based on System.Objectin 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 beconverted to object and back again to int. This example shows bothboxing and unboxing. When a variable of a value type needs to beconverted to a reference type, an object box is allocated to hold thevalue, and the value is copied into the box. Unboxing is just theopposite. When an object box is cast back to its original value type,the value is copied out of the box and into the appropriate storagelocation.

AUTOMATIC BOXING:

In reality is there any need for boxing andunboxing? In practical situation we don't need to box data types allthat often,if ever.In fact ,most of the time ,the C# compilerautomaticallyboxes and unboxes variables when appropriate.For example,if we pass a value type into a method requiring an object parameter,boxing occurs behind the curtains:

// Assume the following method :

public static void Arun(object o)
int x=99;
Arun(x); // Automatic Boxing.

CONCLUSION:

At times ,Boxing and Unboxing can beexplicitly to help improve the performance of your application.In realtime applications boxing and unboxing takes place automatically and insome situations such as to convert a structure to an object refrence weneed it.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!