String Is Nothing versus String = Nothing

  • Thread starter Thread starter John A Grandy
  • Start date Start date
J

John A Grandy

do these mean the same thing ?

Dim s As String
.....

If s Is Nothing Then
.....

If s = Nothing Then
.....
 
Yes and no....

-----------------------------------
Dim s as String

Debug.WriteLine(s is Nothing) ' True
Debug.WriteLine(s = Nothing) ' True
Debug.WriteLine(s = "") ' True

s = "" ' Same as s = String.Empty

Debug.WriteLine(s is Nothing) ' False
Debug.WriteLine(s = Nothing) ' True

------------------------------------

"s = Nothing" tests to see if it is not assigned to anything OR is equal to
""
"s is nothing" only tests to see if it is not assigned to anything

i.e.
--------------------------

If s = nothing then
.....

' is equlvelent to

If s is nothing orelse s = String.Empty then
....
--------------------------

If you want short code to test for empty strings, use

If s = "" then

but beware of performance if doing this in a big loop because of string
comparisons. The following may have a slight performance advantage:

If s is nothing orelse s.Length = 0 then


HTH,

Trev.
 
Hi John,

No
Try this
\\\
Dim s As String
If s Is Nothing Then MessageBox.Show("IsNothing")
If s = Nothing Then MessageBox.Show("=Nothing")
s = ""
If s Is Nothing Then MessageBox.Show("IsNothing2")
'Isnothing 2 Will not be showed
If s = Nothing Then MessageBox.Show("=Nothing2")
'=Nothing is true
//
I hope this helps?

Cor
 
<<<
The following may have a slight performance advantage:

If s is nothing orelse s.Length = 0 then
why not use

If s = Nothing Then
 
why not use
If s = Nothing Then

Because if s is not nothing, then a string comparison is done to check if it
is equal to "" wich is slower than checking the length.

If s = Nothing Then

is the same as

If s is Nothing orelse s = "" Then

where as if you use

If s is Nothing orelse s.Length=0 Then

you cut out the s = "" string comparison.

The performance advantage is really small though and will unlikley make any
difference in a real world application (on my machine it averages out about
1/50 sec for 200000 iterations).



HTH,

Trev.
 
* "John A Grandy said:
do these mean the same thing ?

Dim s As String
....

If s Is Nothing Then
....

If s = Nothing Then
....

In addition to the other replies -- you can query old messages of this
group using Google Groups Search (<http://www.deja.com>). Just select
this group (microsoft.public.dotnet.languages.vb) in the advanced groups
search and "feed" Google with the keywords. I remember there were some
threads about this topic in the past.
 
Back
Top