Understanding Boxing & Unboxing Day 22

Lecture 22 : Understanding Boxing & Unboxing


Boxing :
  • Boxing is used to store value types in the garbage-collected heap.

  • Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type.

  • Boxing a value type allocates an object instance on the heap and copies the value into the new object.

  • Consider the following declaration of a value-type variable :

                                  int i = 123;
  • The following statement implicitly applies the boxing operation on the variable i :

          // Boxing copies the value of i into object o.

                               object o = i;
  • The result of this statement is creating an object reference o, on the stack, that references a value of the type int , on the heap. 

  • This value is a copy of the value-type value assigned to the variable i. 

  • The difference between the two variables, i and o, is illustrated in the following image of boxing conversion :


  • It is also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required :

           int i = 123;
           object o = (object)i;  // explicit boxing
  • This example converts an integer variable i to an object o by using boxing. 

  • Then, the value stored in the variable i is changed.

Unboxing :
  • Unboxing is an explicit conversion from the type object of a value type or from an interface type to a value type that implements the interface. 

  • An unboxing operation consists of :

       1)Checking the object instance to make sure that it is a boxed value of the given value type.
       2)Copying the value from the instance into the value-type variable.
  • The following statements demonstrate both boxing and unboxing operations :

           int i = 123;      // a value type
           object o = i;     // boxing
           int j = (int)o;   // unboxing
  • The following figure demonstrates the result of the previous statements :


  • For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type.

Program-

  • Performance Profile :




Comments

Popular posts from this blog

Basic Concept In C Sharp Day 16

VS Code In JavaScript Day 6

ASP.NET MVC Interview Questions Part - II Day 26