Pages

Friday, May 4, 2012



Boxing And UnBoxing:

In this Article, I am going to explain the concept of Boxing and UnBoxing. This is one of type casting technique

              C# provides us value types and reference types. Converting value type to reference is called as Boxing. Converting from reference type to value type is called UnBoxing.

With this concept we can link between value types and reference types by converting value type to reference type and vice-versa.

Value types:

Value type variables directly contain their values. All value types are stored in stack and derived from System.ValueType. Structures and enum also derived form System.ValueType and stored in stack so those are also called Value Types.

Value types are primitive types those re aliases of the .NET Framework System types. For example, int  is an alias of System.Int32

Example: System.ValueType x = 10;

When we compile this line of code, compiler will takes x as of System.Int32 by default.

Reference Types:
Reference type variables store the address of the data. All reference types are stored in heap and derived from System. Object. All classes are reference types.
Because reference types represent the address of the data rather than the data itself, assigning a reference variable to another doesn’t copy the data. Instead, assigning a reference variable to another instance creates a second copy of the reference, which refers to the same location of the heap as the original value:
Boxing:

While boxing any value from value type to reference type, we can do implicit or explicit casting. Implicit boxing means you no need to inform the complier that you are boxing from value type to object. Right Now I am giving below example for “Implicit Typecasting

Ex:   int x = 30;
       Object o = x;
       Console.writeline (“Object value after boxing {0}”, o) // prints 30

      // Explicit Typecasting…
      Int y = 50;
      Object e = (Object) y;
      Console.WriteLine (“Object value after typecasting {0}”, e) // prints 50

UnBoxing:

Let we see how to do un Boxing. While converting the reference type to value type, we cannot use the implicit type casting. To do Unboxing any reference value we must use the explicit type casing only. See the below example.

Ex:  int x = 5;
       Object o1 = x; //boxing
       Int y = o1; // gives error
       Int y = (int) o1; //
       Console.WriteLine (“y value after unboxing.. {0}”, y); // prints 5


For an unboxing conversion to a given value-type to succeed at run-time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value-type.

  Ex: int32 x = 10;
       Object ob1 = x; //boxing
       Int64 y;
       y = (int) ob1; // unboxing
      
This code complies successfully but while executing, gives InvalidCastException. So the type variable used for boxing will be same when unboxing the value

 



No comments:

Post a Comment