Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String <> Nothing And String <> "" Redundant in VB .NET?

Tags:

vb.net

I looking at some code and came acorss this:

Dim TestString As String
...
If TestString <> Nothing And TestString <> "" Then
...
EndIf

Are both conditions checking the same thing?

Thanks

like image 851
Erich Peterson Avatar asked Jul 02 '12 02:07

Erich Peterson


2 Answers

Nothing would be no string at all (null in other languages), which is different than an empty string (""), which is actually a string.

However, the check should be replaced with If Not String.IsNullOrEmpty(TestString) Then, which makes it clearer what exactly you are doing.

I just played around with this some in LINQPad, and found something mildly surprising. In VB.NET:

Dim s1 as string = Nothing
Dim s2 as string = ""

Console.WriteLine(s1 is Nothing) 'True
Console.WriteLine(s2 is Nothing) 'False

Console.WriteLine(s1 = "") 'True
Console.WriteLine(s2 = "") 'True

Console.WriteLine(string.IsNullOrEmpty(s1)) 'True
Console.WriteLine(string.IsNullOrEmpty(s2)) 'True

In C#:

string s1 = null;
string s2 = "";

Console.WriteLine(s1 == null); //True
Console.WriteLine(s2 == null); //False

Console.WriteLine(s1 == ""); //False
Console.WriteLine(s2 == ""); //True

Console.WriteLine(string.IsNullOrEmpty(s1)); //True
Console.WriteLine(string.IsNullOrEmpty(s2)); //True

I wasn't quite expecting that. It appears that VB.Net treats an Nothing as an empty string. My guess is for compatibility with older versions of VB.

This reinforces all the more that you should be using String.IsNullOrEmpty for these sorts of checks, as it is more explicit what you are checking for, and works as expected.

like image 72
Matt Sieker Avatar answered Oct 28 '22 13:10

Matt Sieker


They are checking the samething, but they MIGHT be meant to check different things.

If IsNothing(TestString) Then

And

If TestString = Nothing Then

Are different test -- the first is seldom used, because typicaly you only really want to know if it has a non-empty value. But it can be used for treating an empty string anf a null value differently in a DB, or for detecting usage of an optional parameter (both cases requiring extra work to make sure that you don't inadvertantly slip in a wrong value, so somewhat fragile).

In the example given, the test is actually a bit wordy and confusing, if that's what you want to test then If String.IsNullOrEmpty(TestString) Then

Is the way to go about it. If that "and" was supposed to be an "or" then it might make sense to have used IsNothing(TestString).

like image 27
jmoreno Avatar answered Oct 28 '22 11:10

jmoreno