No...">

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

I look at some code and come to this:

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

Do both conditions test the same thing?

thanks

+6
source share
3 answers

They test rashes, but they MAY be meant to test different things.

 If IsNothing(TestString) Then 

AND

 If TestString = Nothing Then 

Are different tests - the first is rarely used, because typically you really want to know if it has a non-empty value. But it can be used to process an empty string and in different ways in the database, or to determine the use of an optional parameter (both cases require additional work to make sure that you are not mistakenly slipping in the wrong value, therefore it is somewhat fragile).

In the above example, the test is actually laconic and confusing if this is what you want to check then If String.IsNullOrEmpty (TestString) Then

This is a way around this. If this "and" should have been "or", then it would be wise to use IsNothing (TestString).

+7
source

Nothing will not be any string at all ( null in other languages), which is different from the empty string ( "" ), which is actually a string.

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

I just played with it in LINQPad and found something slightly 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 did not expect this. It looks like VB.Net treats Nothing as an empty string. My guess is compatibility with older versions of VB.

This reinforces the fact that you should use String.IsNullOrEmpty for these kinds of checks, since it is more explicit that you are checking and works as expected.

+14
source

Yes, by definition in VB.NET "" equivalent to Nothing , including for = , <> and all VB functions; unless you explicitly care about the difference, for example by checking with Is .

Of course, you will see differences when using common .NET functions, and especially the methods in which str.Method terminates using the Null Reference exception.

BTW I would suggest that excerpt in OP is C # (poorly) converted code.

+3
source

Source: https://habr.com/ru/post/919466/


All Articles