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
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.
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).
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