Boxing and Unboxing Types

Even the simple value types like int in C# can be thought of as objects. In fact, there are formal terms for the conversion of value types into reference types (that is, objects) and back again boxing and unboxing .

Boxing a value type is the conversion of that value type into the type object . Boxing is implicit, which means the compiler will do it for you. For example, say you pass an integer to WriteLine in this code, where temperature is an int variable:

 System.Console.WriteLine("The temperature is {0}", temperature); 

In the case where you use a format string with WriteLine , WriteLine is actually expecting you to pass an object after the format string. When you pass an int , C# will box it into an object, and call that object's ToString method.

Whereas boxing is implicit, unboxing the process of converting from an object back to a simple typemust be explicit, using a type cast. You can see an example of both boxing (implicit) and unboxing (explicit) in ch04_07.cs, Listing 4.7.

Listing 4.7 Boxing and Unboxing (ch04_07.cs)
 public class ch04_07 {   static void Main()   {  int int1 = 1;   object obj1 = int1;   //Boxing   int int2 = (int) obj1;  //Unboxing  } } 

You can see the boxing and unboxing taking place in the MSIL for the Main method in ch04_07.cs:

 .entrypoint // Code size    18 (0x12) .maxstack 1 .locals init (int32 V_0,      object V_1,      int32 V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0  IL_0003: box    [mscorlib]System.Int32  IL_0008: stloc.1 IL_0009: ldloc.1  IL_000a: unbox   [mscorlib]System.Int32  IL_000f: ldind.i4 IL_0010: stloc.2 IL_0011: ret 

Microsoft Visual C#. NET 2003 Kick Start
Microsoft Visual C#.NET 2003 Kick Start
ISBN: 0672325470
EAN: 2147483647
Year: 2002
Pages: 181

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: