Skip to Content
Programming Visual Basic .NET, Second Edition
book

Programming Visual Basic .NET, Second Edition

by Jesse Liberty
April 2003
Intermediate to advanced
560 pages
14h 4m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET, Second Edition

Boxing and Unboxing Types

Boxing and unboxing are the processes that enable value types (e.g., integers) to be treated as reference types (objects). The value is “boxed” inside an Object and subsequently “unboxed” back to a value type. It is this process that allowed you to call the ToString( ) method on the integer in Example 6-4.

Boxing Is Implicit

Boxing is an implicit conversion of a value type to the type Object. Boxing a value allocates an instance of Object and copies the value into the new object instance, as shown in Figure 6-4.

Boxing value types

Figure 6-4. Boxing value types

Boxing is implicit when you provide a value type where a reference is expected. The compiler notices that you’ve provided a value type and silently boxes it within an object. You can, of course, explicitly cast the value type to a reference type, as in the following:

Dim myIntegerValue As Integer = 5
Dim myObject As Object = myIntegerValue ' explicitly cast to object
myObject.ToString( )

This is not necessary, however, as the compiler will box the value for you, silently and with no action on your part:

Dim myIntegerValue As Integer = 5
myIntegerValue.ToString( ) ' boxed for you

Unboxing Must Be Explicit

To return the boxed object back to a value type, you must explicitly unbox it if Option Strict is On (as it should be). You will typically unbox by using the DirectCast( ) function or the CType( ) function. Figure 6-5 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET

Programming Visual Basic .NET

Dave Grundgeiger
VB.NET Language in a Nutshell, Second Edition

VB.NET Language in a Nutshell, Second Edition

Steven Roman PhD, Ron Petrusha, Paul Lomax

Publisher Resources

ISBN: 0596004389Supplemental ContentCatalog PageErrata