Boxing and UnBoxing



  • Boxing is the process of converting a variable from value type to reference type
  • Unboxing is the process of converting a variable from reference type to value type

Difference between boxing and Unboxing


SNo
            Boxing
                    Unboxing
01
Converting a variable from Value Type to Reference Type
Converting a variable from Reference Type to Value Type
02
Supports 2 types
1.     Implicit Boxing
2.     Explicit Boxing
Supports only 1 Type
1.     Explicit Unboxing
03
Boxing is 20 times Costlier than normal Initialization
Unboxing is 4 times Costlier than normal Initialization

Example 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CABASCIS
{
    class ClsBoxing
    {
        static void Main()
        {
            int b = 10;
            object O = b; //implicit Boxing
            object X = (object)b; //Explicit Boxing
            int u = (int)O; //Explicit Unboxing
            Console.WriteLine("Value of b is :- " + b);
            Console.WriteLine("value of O is :- " + O);
            Console.WriteLine("value of X is :- " + X);
            Console.WriteLine("value of u is :- " + u);
            Console.Read();
        }
    }
}



Output :-



  • Boxing is 20 times costlier than normal initialization, because whenever a boxing is done following tasks will be performed internally
       1. Runtime will search for the respective data within the stack
       2. A copy of this value is made into Heap
       3. Reference to this copy is maintained from the object variable
  • Unboxing is 4 times costlier than normal initialized because, when Unboxing is made following tasks are performed internally
          1. Object referenced value is searched within the Heap
          2. A copy of this is made into stack

When to use Boxing and Unboxing:
  • As boxing and Unboxing is costlier process, than normal initialization so Boxing and Unboxing should be avoided in maximum situations use only if necessary, but we should use Boxing and Unboxing in case other operations are costlier (takes more time) than Boxing and Unboxing




No comments:

Post a Comment