Spot the Bug! – Much Ado about Nothing… (Jonathan Aneja)

Microsoft has this neat mailing list called “Spot the Bug” where developers can send interesting snippets of code that look correct but actually have subtle bugs in them.  The puzzles are a lot of fun and I’ve always thought it’d be a fun thing to try here on the team blog.  Over the past year or so I’ve been keeping a list of interesting bug reports and emails where people have been tripped up by some of VB’s hidden subtleties (though admittedly many of these could apply to C# as well).


 


The format’s gonna be a bit of an experiment – let me know if you prefer to see the answer in the same post or posted a day later.  Alright let’s get started…


 


Spot the Bug: 


The following code is intended to print “Yes” – will it?


 


        Dim x As Integer? = Nothing


 


        If x = Nothing Then


            MsgBox(“Yes: x contains null”)


        Else


            MsgBox(“No: x does not contain null, and has a real value”)


        End If


 


.


 


.


 


.


 


.


 


.


 


Answer:  No!  We’re using the equality operator to compare a nullable integer with Nothing – this results in null propagation, i.e. the result of the expression is Nothing.  An If-statement attempts to convert its condition to a Boolean, so basically we’re left with this:


 


        If Nothing Then


 


        Else


            ‘Obviously we’ll always land here


        End If


 


This can be really surprising when working with nullables, so we’ve decided to add a warning for this case in VB10:


 New null-popagation warning in VB10



 


The warning explains the fix – use “Is” instead of = to avoid the null propagation and get the semantics you expect:


        Dim x As Integer? = Nothing


 


        If x Is Nothing Then


            MsgBox(“Yes: x contains null”)


        Else


            MsgBox(“No: x does not contain null, and has a real value”)


        End If


 


Check back for a similar case but with a bit of a twist tomorrow…