Asp.net what is Boxing and Unboxing in C#

Explain Boxing and Unboxing in C#:



Boxing and unboxing is a central concept in C#’s type system. It provides a binding link between value-types and reference-types by permitting 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.

Boxing and unboxing is an essential concept in .NET’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.

  • Converting a value type to reference type is called Boxing. 
  • Unboxing is the opposite operation and is an explicit operation.



.NET 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.

Example of boxing and Unboxing:

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

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.

Other Asp.net related post:



Comments

Popular posts from this blog