0

Recently I've noticed that when we've been doing string comparisons in our .NET code we have been safeguarding against null references. This check seems unnecessary in VB.NET because it overloads the equality operator and performs this null ref check for us. Do you all agree ?

See examples below:

        Dim myStringVariable As String

        ' Unnecessary in VB.NET
        If myStringVariable Is Nothing OrElse myStringVariable = "" Then
        End If

        ' Unnecessary in VB.NET
        If String.IsNullOrEmpty(myStringVariable) Then
        End If

        ' This will work
        If myStringVariable = "" Then
        End If

        ' Also acceptable if you don't like using hard coded constants
        If myStringVariable = String.Empty Then
        End If

3 Answers 3

3

Specifically for equality tests you may be right. However, equality tests are not the only thing you do with strings.

I have not done much VB.Net, but I strongly suspect that

myStringVariable.Length

will blow up if myStringVariable is null, er... Nothing.

Sign up to request clarification or add additional context in comments.

Comments

3

It's never unnecessary to be explicit about what you're doing. If someone who is working on your code reads String.IsNullOrEmpty they know that you meant treat null and empty the same way.

If someone who is working on your code reads myStringVariable = String.Empty, they have to wonder if you meant to handle nulls and empties the same way or if you made an oversight.

Comments

0

You're right, combining all of those checks is hella redundant.

Why not simplify it to simply:

If String.IsNullOrEmpty(myStringVariable) Then
    ' do whatever
End If

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.