Boxing and unboxing

Posted by Ersudeep13 under .NET Framework category on | Points: 40 | Views : 1250
Boxing--> It is a process of converting a variable from value type to reference type. it supports two types
1)Implicit boxing
2)Explicit Boxing
Boxing is 20 times costlier than normal Initialization.
UnBoxing--> Converting a variable from Reference type to value type. it supports only One type
1)Explicit Boxing
UnBoxing is 4 times Costlier than normal Initialization.

Boxing is 20 times costlier than normal Initialization,because whenever a boxing is done following tasks will be performed automatically.
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 referencedvalue is searched within the Heap.
2)A copy of this is made into stack

programming in C# for Boxing and unboxing

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

namespace box
class Program
static void Main(string[] args)
int i = 10;
object O = i; //Implicit Boxing
object X = (object)i; // Explicit Boxing
int j = (int)O; // Explicit Unboxing
Console.WriteLine("value of i is:-" + i);
Console.WriteLine("value of O after Implicit Boxing is :-" +O);
Console.WriteLine("value of X after Explicit Boxing is :-" +X);
Console.WriteLine("value of j after Explicit UnBoxing is :-" +j);

Comments or Responses

Login to post response