Boxing and Unboxing

Converting a value type to reference type is called Boxing.
Unboxing is the opposite operation
Boxing confirm the conversion of value type variable or literals to the reference type

int i = 12;
object box = i;
if (box is int) {
Console.Write(“Box contains an int”);
}
————————————————–

struct Point
{
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Point p = new Point(10, 10);
object box = p;
p.x = 20;
Console.Write(((Point)box).x);

will output the value 10 on the console
—————————————-
Unboxing:

object box = 12;
int i = (int)box;
object box = new int_Box(12);
int i = ((int_Box)box).value;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s