• Saves Valuable Time
  • Trusted Accuracy for 14 Years
  • 15-Day Money-Back Guarantee

Nullable Inequalities in VB vs C#

Inequality tests in VB using the '<>' operator involving nullable types (System.Nullable with a struct type parameter) behave very differently from the same tests in C# using the '!=' operator. In VB, if the nullable value is 'Nothing', then the conditional always evaluates to 'Nothing', which has the same effect as the conditional being 'False'. In C#, if the nullable value is 'null', then the conditional evaluates to 'true' when comparing to a non-null value.

The root of the inconsistency between VB and C# is that the '==' and '!=' operators are interpreted in C# exactly as if you were calling the System.Nullable 'Equals' method, while the VB '=' and '<>' operators are not, instead relying on the unusual VB language rules. To get the expected conditional results, the correct VB approach would be to use the System.Nullable 'Equals' method.

VB C#
Dim nullInt As Integer? = Nothing
If nullInt <> 0 Then
   'statement doesn't execute!
   MessageBox.Show("not equal")
End If
int? nullInt = null;
if (nullInt != 0)
   //statement executes as expected
   MessageBox.Show("not equal");

The following C# reproduces the VB behavior:

C#
int? nullInt = null;
if (nullInt.HasValue && nullInt != 0)
   //statement doesn't execute
   MessageBox.Show("not equal");

The following VB is a better approach and is equivalent to our original C# code:

VB C#
Dim nullInt As Integer? = Nothing
If Not nullInt.Equals(0) Then
   'statement executes as expected
   MessageBox.Show("not equal")
End If
int? nullInt = null;
if (nullInt != 0)
   //statement executes as expected
   MessageBox.Show("not equal");

Note that you can call a method on a 'null' System.Nullable instance without throwing an exception since nullable instances are never null like reference types are null. Instead, they are generic value types with no value set.


Use Instant C# and Instant VB to convert between VB.NET and C#.     

Additional resource: VB.NET and C# Equivalents


Copyright © 1997 – 2018 Tangible Software Solutions, Inc.