Thursday, May 15, 2008

Boxing and UnBoxing in C#

Boxing and unboxing are essential concepts of .NET type system.

Boxing refers to conversion of value type to reference type.


int i=5;
object o=i; //boxing

Unboxing refers to the conversion of reference type to value -type.


int j=(int)o; //Unboxing & type-casting.


Too much boxing and unboxing hits the application performance. Care must be taken while coding. Try to avoid boxing and unboxing.

See the below code. Does the following code has boxing?


using System;

namespace BoxingDemo
{
class Program
{
static void Main(string[] args)
{
int count = 5;
Console.WriteLine("Count:" + count);
}
}
}

Look at the IL Code generated. It has box instruction. Boxing happens here.

How to avoid it? See the code below & IL generated for it. It has no boxing.

using System;

namespace BoxingDemo
{
class Program
{
static void Main(string[] args)
{
int count = 5;
Console.WriteLine("Count:" + count.ToString());
}
}
}

Be careful!!!
Post a Comment