mitesh sheth
What is the real use of boxing and unboxing?
By mitesh sheth in ASP.NET on Aug 02 2006
  • Aug, 2006 2

    C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

    Value Types

    Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

    Reference Types

    Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.
    Boxing and unboxing is a essential concept in C#’s type system. 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.

    Sometimes we need to convert ValueTypes to Reference Types also known as boxing. "implicit boxing"  means you don't need to tell the compiler that you are boxing Int32 to object because it takes care of this itself although you can always make explicit boxing:

            Int32 x = 10;
            object o = x ;  // Implicit boxing

            Int32 y = 10;
            object obj = (object) y; // Explicit Boxing

            x = o; // Implicit UnBoxing    

    C# provides a unified type system. All types including value types derive from the type object. It is possible to call object methods on any value, even values of primitive types such as int.
    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.

    Thanks!
    Manoj [InfoAxon Technologies Ltd.]

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS