Developer

Put up your fists and start boxing with .NET

Do you know how you can incorporate boxing into your applications? Find out how boxing and unboxing affects your everyday development activities.

Developers are a finicky bunch. It seems we love to throw around new words and concepts, which often leads to confusion for people who are new to the field. One example I've noticed lately is the term boxing, so I'll explain what it means and how you can use it in your apps.

Lace up your gloves

Boxing is the process of explicitly converting a value type into a corresponding reference type. Basically, this involves creating a new object on the heap and placing the value there. Here is a basic example in C#:

int example = 35;
object iExample = example;

The new reference type includes the value 35. Here's how you can accomplish the same process with VB.NET:

Dim example As Integer
Dim iExample As Object
example = 35
iExample = example

Reversing the process is just as easy with unboxing, which converts the value in an object reference on the heap into a corresponding value type on the stack. The unboxing process begins by verifying that the recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to the stack. This is a quick demonstration, using our previous example in C#:

int example = 35;
object iExample = example;
int example2 = (int)iExample;

You may recognize this process as casting, and it does utilize the same syntax. The unboxing process works in VB.NET as well:

Dim example As Integer
Dim example2 As Integer
Dim iExample As Object
example = 35
iExample = example
example2 = iExample
Console.WriteLine("Value: " + example2.ToString())

Notice that I inserted a statement to display the contents in order to prove the operation worked without problems.

Proceed with caution

The unboxing process works with our examples due to the examples' simplicity and tight control of the values utilized. This may not be the case in your application. With that in mind, you should utilize the try/catch blocks to catch any problems encountered during the unboxing process. Attempting an invalid unboxing operation will generate an InvalidCastException. The following C# code shows how you might use it:

try {
int example = 35;
object iExample = example;
 double example2 = (double)iExample;
Console.WriteLine("Value: " + example2.ToString());
} catch (InvalidCastException ex) {
Console.WriteLine("Casting Exception encountered when trying to convert value:
 " + ex.ToString());
} catch (Exception ex) {
Console.WriteLine("Exception encountered when trying to convert value: " +
 ex.ToString());
}

This code throws an exception when attempting to unbox an integer value to a double value type. While C# will complain with an exception, VB.NET continues without any problems. With VB.NET, it's possible to unbox a boxed fundamental type into any other fundamental type that it has a conversion to.

This can be very useful, but it comes at a price. When you convert any value from Object, the program must check at runtime to see whether the value is a boxed fundamental type so that it can apply the special unboxing behavior. These checks add overhead to the conversion, which normally is insignificant. However, if you know ahead of time that the conversion type exactly matches the boxed type, there may be some advantage to avoiding the overhead. For example, when many conversions are being performed, the overhead could become significant.

VB.NET's DirectCast operator allows you to disable unboxing for a value. This operator accepts two parameters: the object to convert and the type to convert to.

Try
Dim example As Object
Dim i1 As Integer = 35
Dim i2 As Integer
Dim lng As Long
example = i1
i2 = DirectCast(example, Integer) ' This is legal
lng = DirectCast(example, Long) ' Throws exception since types do not match
Console.WriteLine("lng: " + lng.ToString())
Catch ex As InvalidCastException
Console.WriteLine("Casting error")
Catch ex As Exception
Console.WriteLine("Exception")
End Try

In practice

You might be wondering how boxing and unboxing affects your everyday development activities. The truth is that, most of the time, boxing and unboxing are performed behind the scenes by the compiler. A good example is the act of passing a value to a method, which may be expecting an object, but you pass a value type. The system handles the conversion (boxing) behind the scenes. On the other hand, you'll need to explicitly unbox the value if you want to access its methods and so forth.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox