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 ...

Get C# Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.