In VB.NET, what is the difference between
if foo is Nothing Then
doStuff()
End If
and
if foo=Nothing Then
doStuff
It depends on the type.
For value types, Is doesn’t work, only =, and Nothing refers to the default instance of that type (i.e. the instance that you get by calling New T() for a given type T).
For reference types, Is performs a reference comparison (identical to object.ReferenceEquals(a, Nothing)). a = Nothing usually does not work, unless Operator = has explicitly been defined for that class.
If, furthermore, Operator = has been implemented correctly, then foo = Nothing and foo Is Nothing should yield the same result (but the same isn’t true for any other value instead of Nothing) but foo Is Nothing will be more efficient since it’s a compiler intrinsic while Operator = will call a method.
For nullable value types (i.e. instances of Nullable(Of T)), special rules apply: like all other operators, = is lifted (notice the error in that blog post …) by the compiler to the underlying type. The result of comparing two Nullables is thus not Boolean but Boolean? (note the ?). However, because of so-called “null propagation” for lifted operators, this will always return Nothing, no matter the value of foo. Quoting the Visual Basic 10 language specification (§1.86.3):
If ether (sic!) operand is
Nothing, the result of the expression is a value ofNothingtyped as the nullable version of the result type.
So if the users want to compare a Nullable variable to Nothing, they must use the foo Is Nothing syntax for which, once again, the compiler generates special code to make it work (§1.79.3 of the Visual Basic 10 language specification).
Hat tip to Jonathan Allen for (correctly) persisting that I was wrong; hat tip to Jared Parsons for passing me a link to the Visual Basic 10 specification.
(The above assumes that Option Strict On is used, as you always should. In case that isn’t the case, the results will differ slightly since calling foo = Nothing may perform a late-bound call.)