Friday, August 5, 2011

Understanding Boxing in console application.

The .NET Framework enables you to convert an object from a value type into a reference type and then convert the object back into a value type later. The conversion of an object from a value type to a reference type is called boxing, and the conversion of an object from a reference type back to a value type is called unboxing.

Boxing:
Boxing occurs automatically when you assign a value-type object to a reference-type variable. The CLR creates a copy of the value-type object on the managed heap, and the reference-type variable refers to the copy of the object on the managed heap.

Boxing occurs in the following typical scenarios:
• When you pass a value-type object into a method that requires a System.Object or Interface-type parameter. System.Object and interfaces are reference types. Therefore, a method that expects a System.Object or interface-type parameter requires an object that is allocated on the managed heap.
• When you add a value-type object to a nongeneric collection such as System.Collections.ArrayList. Nongeneric collections store System.Object references to the objects in the collection. Therefore, when you add a value-type Object to the collection, the collection requires an object that is allocated on the managed heap.

Following example shown.

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

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
//boxing
int x = 12;
object o = x;
Console.WriteLine(o);
Console.ReadLine();
}
}
}



Output is display below:

No comments:

Recent Posts