Microsoft LINQ Books

Programming Microsoft LINQ & Introducing Microsoft LINQ
Welcome to Microsoft LINQ Books Sign in | Join | Help
in Search

Marco Russo

VB9 changes in nullable types conversion

The Beta 2 of Visual Basic 9 changed the way it handles nullable types conversion. In our Introducing Linq book (based on Beta 1 of Visual Studio 2008) we wrote that it wasn't possible to assign a nullable value to the corresponding non-nullable type without using a cast. This was the code in Listing 3-2.

    Dim k As Integer? = 16
    Dim p As Integer = k                        ' Compiler error
    Dim q As Integer = DirectCast( k, Integer ) ' Ok
    Dim r As Integer = CType( k, Integer )      ' Ok

As we described in the corrections document, nullable types weren't ready in Beta 1 and was delayed for a following beta (code in Listing 3-1 and Listing 3-2 does not work in Beta 1).

In Beta 2 nullable types has been implemented, but the behavior for nullable type conversion slightly changed from what we described. More precisely, we have a different behavior depending on the Option Strict setting. With Option Strict On we can only use CType to do the conversion, otherwise a compiler error is generated.

    Dim k As Integer? = 16
    Dim p As Integer = k                        ' Compiler error
    Dim q As Integer = DirectCast( k, Integer ) ' Compiler error
    Dim r As Integer = CType( k, Integer )      ' Ok (exception if k is Nothing)

With Option Strict Off, you can assign a nullable value to the corresponding non-nullable type. In case the value is null, an exception will be thrown during execution, just like CType do. If you want to be sure that the conversion is safe (and doesn't throw an exception during execution) you can use DirectCast, which emits a compiler error if a similar conversion is made. Look at the comments in the following code:

    Dim k As Integer? = 16
    Dim p As Integer = k                        ' Ok (exception if k is Nothing)
    Dim q As Integer = DirectCast( k, Integer ) ' Compiler error
    Dim r As Integer = CType( k, Integer )      ' Ok (exception if k is Nothing)

Published venerdì 12 ottobre 2007 20.18 by Marco.Russo

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems