What is boxing and unboxing in C#.NET? Explain briefly with sample code.

 Posted by Nagasundar_Tn on 11/29/2012 | Category: C# Interview questions | Views: 8195 | Points: 40
Answer:

Boxing is a process of converting value type variable to reference type or object type. The boxing can be done implicitly or explicitly.
Implicit boxing means the type casting or conversion can be done automatically where as explicitly can be done by manual type casting.

Unboxing is an explicit conversion from reference type to a value type. It has to be done explicitly.

Please look at the following example:

static void Main(string[] args)

{
#region Boxing
int intVariable = 10;

object objImplicitBoxing = intVariable; //Implicit Boxing
object objExplicitBoxing = (object)intVariable; //Explicit Boxing

Console.WriteLine(string.Format("Implicit Boxing {0}",objImplicitBoxing));
Console.WriteLine(string.Format("Explicit Boxing {0}",objExplicitBoxing));
#endregion

#region Unboxing
int iUnbox = (int)objImplicitBoxing; //Explicit Unboxing
Console.WriteLine(string.Format("Explicit Unboxing {0}",iUnbox));
#endregion
}


From the above code:

object objImplicitBoxing = intVariable;   


The above line indicates assigining the integer value to object DIRECTLY.


object objExplicitBoxing = (object)intVariable;


The above line type casts the integer value to object and assigning to another object.

int iUnbox = (int)objImplicitBoxing;	


The above line type casts the object to Integer value and assigning to Integer variable.


Asked In: SRA systems | Alert Moderator 

Comments or Responses

Login to post response