BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Visual Basic and C#: Differences in Nullable Types

Visual Basic and C#: Differences in Nullable Types

Bookmarks

When .NET 1.0 was released, VB and C# were very similar. But with the fourth version nearing release, the differences are really mounting. Today we look at the subtle differences in nullable types that can trip up developers.

Nullable types were introduced with .Net 2.0. Using generics, any value type can be wrapped in Nullable, allow it to have a null value. Previously this could only be done by creating a custom class or boxing the value and assigning it to a variable of type object.

C# immediately added language support for nullable types. VB, still dealing with the fallout from the VB to VB.Net transition, was unable to do likewise. Nullables can still be used, but only at the API level.

With version 9, Visual Basic will add full support for nullable types. It will use a syntax nearly identical to C#, but with very different semantics. With C#, comparison operations always returns a true or false. In VB, nulls are propagated and thus a comparison may return true, false, or null.

 a=null, b=null
Operator C# Result  VB Result 
 == true   Nothing
 !=  false  Nothing
 >  false  Nothing
 <  false  Nothing
 >=  false  Nothing
 <=  false  Nothing

 a=1, b=null
Operator C# Result  VB Result 
 == false  Nothing
 !=  true  Nothing
 >  false  Nothing
 <  false  Nothing
 >=  false  Nothing
 <=  false  Nothing

These tables show an interesting anomaly in C#. While a==b returns true when both are null, a>=b and a<=b return false.

When it comes to checks requiring Booleans, C# is clear. VB, on the other hand has to somehow map its three-state logic to a Boolean value. It does this by equating null with false for the purpose of Boolean checks like If, While, and Until. This can lead to surprising results of its own.

a = null, b = null 
If a=b Then
'skipped
Else
'this line is executed
End if

If Not (a=b) Then
'skipped
Else
'this line is executed
End if

Both (a=b) and Not (a=b) return a null, and thus are considered to be false.

Knowing these differences and inconsistencies by heart is essential for developers working with nullable types in either language, lest subtle bugs be introduced.

Rate this Article

Adoption
Style

BT