Boxing vs UnBoxing in CSharp

Introduction 

Before dive into the topic i.e. Boxing vs UnBoxing , Lets understand that datatypes are broadly divided into 2 types.

  • Value Type
  • Reference Type
Lets Get Started

Value type - : Value type is nothing but the type which stored in Stack.
Reference Type-: Reference type is nothing but the type which stored in Heap.

using System;
using System.Text;
namespace TestApplication{  
    class Program
    {
        public static void Main(string[] args)
        {
            int intval = 10;
            object objref = intval;//Boxing
            intval = (int)objref;//Unboxing
            Console.ReadKey();
        }         
    }
}




See the above code. In Boxing we are assign a value to an object Where in Unboxing we assign the object type to the integer.

In Boxing compiler will cast the type which is called Implicit conversion as below.
object objref = 10;

In UnBoxing compiler will not cast the type which is called Explicit conversion.
object objref = 10;
int intval = (int)objref;

See the below figure which demonstrate the boxing and unboxing. 
Fig-1

In Fig-1 demonstrated the data from Heap to Stack and Stack to heap which is in the other way we called Unboxing and Boxing respectively.

Things to remember

  • Boxing and Unboxing degrade the Performance.
  • Use Generic to avoid Boxing and UnBoxing.
  • For Boxing Implicit conversion takes place.
  • For UnBoxing Explicit conversion takes place.
  • Try to avoid boxing and Unboxing as much as possible.




Thanks...............



















Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts