In yesterday’s post we saw that the use of the wrong comparison operator with Nothing in an If block can lead to surprising results. Let’s look at a slightly different case today:
Dim x As Integer = Nothing
If x = Nothing Then
MsgBox(“A true statement – we land here”)
Else
MsgBox(“The statement is a lie – we land here”)
End If
What gets printed? If the code is intended to print “A true statement…”, is there actually a bug in this code?
.
.
.
.
.
Answer: The code is correct according to its “specification” (I’m using the term loosely here J), so from a technical point of view there is no bug here. However, from a code readability and maintenance point of view, I’d argue that there is a bug.
The Nothing literal in VB means “default value for this type”, and for an Integer that would be 0. So the code above is exactly equivalent to this:
Dim x As Integer = 0
If x = 0 Then
MsgBox(“A true statement – we land here”)
Else
MsgBox(“The statement is a lie – we land here”)
End If
Now that’s way more readable than the version above, and dramatically reduces the potential for confusion. In general*, if you ever find yourself writing “= Nothing” in a conditional expression, you should either be changing the = to “Is” (as we saw yesterday), or you should change Nothing to the actual default value if possible.
The next post will have a real bug, I promise J
*Yes, there may be cases such as structure/generics/overloaded operators where you actually would want to say “= Nothing” – my point is that if you’re going to do this make sure you know what you’re doing, and insert a comment so that those reading your code also know what you’re doing J.
0 comments
Be the first to start the discussion.