Sunday, 5 June 2011

Concept of boxing and Unboxing in C sharp

Boxing and Unboxing concept in C# language. Explaining with code.

Boxing: Boxing refers to the process of moving from a value type to reference type.
Un-Boxing: Un-Boxing refers to the process of moving from a reference type to value type.
Ex:
Public void BoxingUnbox()
{
            int i = 10;
            object obj = i;//boxing
            int j = (Int32)(obj);//un-boxing
}
 But in context of performance using boxing and unboxing is not a good practice.
Now below code illustrate the boxing and simple assignment of value by showing the timer. The code is tested on 10000 values. See below code:
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter choice box/nobox");
            string readkey = Console.ReadLine();
            if (readkey == "box")
            {
                Stopwatch obj = new Stopwatch();
                obj.Start();
                for (int start = 0; start <= 10000; start++)
                {
                    BoxUnbox.Program obj1 = new Program();
                    obj1.box();
                }
                Console.WriteLine(obj.Elapsed.ToString());
                Console.ReadLine();
            }

            else
            {
                Stopwatch obj = new Stopwatch();
                obj.Start();
                for (int start = 0; start <= 10000; start++)
                {
                    BoxUnbox.Program obj1 = new Program();
                    obj1.simpleassignment();
                }
                Console.WriteLine(obj.Elapsed.ToString());
                Console.ReadLine();
            }
       
        }

        public void box()
        {
            int i = 123;
            object j = i;
        }
        public void simpleassignment()
        {
            int i = 123;
            int j = 123;
        }
    }

No comments:

Post a Comment