O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Boxing allows ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required