Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nothing equals String.Empty, null does not equal String.Empty, what am I missing here?

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?

like image 943
Abel Avatar asked Jun 28 '10 09:06

Abel


1 Answers

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.

like image 118
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet