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?
Nothing
has a special meaning in VB for strings. To test whether a string reference is null, you need:
If value Is Nothing
From the VB comparison operators documentation:
Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).
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
If value = Nothing
is compiled to a call to Microsoft.VisualBasic.CompilerServices.Operators.CompareString
which returns 0 (i.e. equal) if one operand is null and the other is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With