November 2004 - Posts

Mike Tyson and C#

An interesting terminology that I came across while going through the C#LS was "boxing" and "unboxing". Though some may be familiar with these terms, I am new to it.

C# has a "unified type system". ie. all types including primitive ones derive from the type "object". A simple example would be:

class UTSDemo
{
 static void Main() {
  Console.WriteLine(333.ToString());
 }
}

The above sinppet calls the method ToString on the integer literal 333 which results in the output "333".

class Boxing
{
 static void Main() {
  int intVal1 = 123;
  object myObj = i;  // boxing
  int intVal2 = (int) myObj; // unboxing
 }
}

From the above example it is clear that an int value can be converted to an object and then back to an int. This is nothing but boxing and unboxing [Mike doesnt know this one ;-)] When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

So using this you could write a method which has object type as its parameters or as the return type when you want to make the method general irrespective of the type.

with 1 Comments