In a mixed code project (VB and C#) we were debugging some old Visual Basic code like this:
If Request.Params("xxx") <> "" Then
'do something
I considered this a bug as Request.Params could be null, in which case the statement would’ve become false which wasn’t the idea.
So I thought. I just found out — again — that VB’s Nothing and C#’s null are not the same things and Nothing is not the same as null. In fact:
if(String.Empty == null) // in C# this is always false (correct)
If String.Empty = Nothing Then ' in VB this is always true (????)
How is this even possible? Is this some backward compatibility issue?
Nothinghas a special meaning in VB for strings. To test whether a string reference is null, you need:From the VB comparison operators documentation:
I suspect this is just for backward compatibility with VB6 – it’s not something I’d be happy with, if I were a VB developer.
A comparison of the form
is compiled to a call to
Microsoft.VisualBasic.CompilerServices.Operators.CompareStringwhich returns 0 (i.e. equal) if one operand is null and the other is empty.