Checking for IsNullOrEmpty or is Nothing

In VB .net is it better is it better to check a string for IsNullOrEmpty rather than checking for a Nothing value? Look at the two different code blocks below . Which is better, 1 or 2?

If Not strMyString Is Nothing Then
End If

If Not String.IsNullOrEmpty(strMyString) Then
End If
Who is Participating?
ste5anSenior DeveloperCommented:
*cough* not better. Different

Test 1 only tests whether the string is Null (Nothing), but not whether it is empty.
Test 2 tests for non empty strings. This implies it is also not null.

Module Module1
    Sub Main()
        Dim Test = ""
        If Not Test Is Nothing Then
            Console.WriteLine("Not Is Nothing")
        End If

        If Not String.IsNullOrEmpty(Test) Then
            Console.WriteLine("Not IsNullOrEmpty")
            Console.WriteLine("another hmm?")
        End If

    End Sub
End Module

Open in new window

NorieVBA ExpertCommented:
It really depends what you want to check I suppose.

I think, (1) would  check if the string hadn't been set and (2) would check if it's an empty string, "" or Null.

So (2) is probably the most appropriate if you want to check the value of the string.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.