Saturday, November 13, 2010

C#.net - Boxing and UnBoxing in C#.net

In this article I will explain the concepts of Boxing and UnBoxing. C# provides us with value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Value Type
Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32,double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types
Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

Boxing Example


 int Val = 11;
 object Obj = Val; // boxing

 System.Console.WriteLine("The Object = " + Obj);

The first line we created a Value Type Val and assigned a value to Val. The second line , we created an instance of Object Obj and assign the value of Val to Obj. The above operation (object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.

UnBoxing Example

 int ValUnBox = (int)Obj; // unboxing

 System.Console.WriteLine("The UnBox Value = " + ValUnBox); 

The first line (int ValUnBox = (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.


Full Source Code

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

namespace ConBoxingUnBoxing
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Boxing Section

                    int Val = 11;
                    object Obj = Val; // boxing

                    System.Console.WriteLine("The Object = " + Obj);


            #endregion

            #region UnBoxing Section

                    int ValUnBox = (int)Obj; // unboxing

                    System.Console.WriteLine("The UnBox Value = " + ValUnBox);   

            #endregion
        }
    }
}

Download
Download Source Code

No comments:

Post a Comment