By Arun GG
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. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.
AUTOMATIC BOXING:
In reality is there any need for boxing and unboxing? In practical situation
we don't need to box data types all that often,if ever.In fact ,most of the time ,the C# compiler automaticallyboxes 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 be explicitly to help improve the performance of your application.In real time applications boxing and unboxing takes place automatically and in some situations such as to convert a structure to an object refrence we need it.