Boxing and Unboxing

   


As mentioned in the previous analysis, C# automatically transforms a value type into a reference type when required. This process is called boxing while the reverse is called unboxing.

In line 46 of Listing 18.1, we created the myTime struct of type TimeSpan with the value 43403. To allow WriteLine to call myTime's ToString method, C# boxed myTime inside an instance of type System.Object as illustrated in Figure 18.1. WriteLine then called ToString for this instance, which, through dynamic binding, invoked the ToString method we defined in lines 27 39 of Listing 18.1.

Figure 18.1. Boxing the TimeSpan structure.
graphics/18fig01.gif

Boxing allows us to assign not only class but also struct-based values to a variable of type System.Object. For example, we can assign myTime to the following variable obj of type System.Object:

 System.Object obj = myTime; 

We can then call the ToString method of obj, which will call ToString of TimeSpan through dynamic binding

 string myTimeString = obj.ToString(); 

This is a powerful scenario that has many uses. For example, we can declare an array of type System.Object and thereby store any value (whether reference or value based) in the elements of the array. We could also define a method with a formal parameter of type System.Object. This method would accept any argument, whether value or reference based.

It is possible to unbox a value type, but, whereas boxing is implicit, unboxing must be done explicitly with the cast operator, as demonstrated in Listing 18.2.

Listing 18.2 UnboxingTest.cs
01: using System; 02: 03: class TestUnboxing 04: { 05:     public static void Main() 06:     { 07:         int myInt = 3422; 08:         int yourInt; 09: 10:         object obj = myInt; 11:         yourInt = (int)obj; 12: 13:         Console.WriteLine("Value of yourInt: {0} ", yourInt); 14:     } 15: } Value of yourInt: 3422 

Line 10 implicitly boxes myInt into System.Object, whereas the cast operator must be used explicitly in line 11 to unbox myInt and assign its value to yourInt. Notice that if obj in line 11 didn't contain an int, the runtime would generate an InvalidCastException.

Note

graphics/common.gif

In general, structs are more efficient in their use of memory than classes. However, to box and unbox a struct requires a bit of additional computer resources. It is more expensive to assign a struct value than a class instance to a variable of type System.Object, because the class instance does not involve boxing during this assignment process. So, if you are likely to, for example, store many values of a particular struct in an array with elements of type System.Object, you should consider changing this struct to a class to improve the performance.



   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net