3

I have the following short piece of code that is never returning the string "selected".

Protected Function SelectedType(ByVal val As String) As String
    If val <> String.Empty Then Return "selected"
End Function

However, if I change it to this, it works. Is there anything wrong when my shorthand code above? -Thanks

Protected Function SelectedType(ByVal val As String) As String
    If Not String.IsNullOrEmpty(val) Then
        Return "selected"
    End If
End Function
0

3 Answers 3

4

String.Empty is "", null is Nothing.

you can compare if a string is null, if it's empty, or both at the same time with IsNullOrEmpty ()

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

3 Comments

so: If Not String.IsNullOrEmpty(val) Then Return "selected"?
btw I'm trying to keep it on a single line
yes, that's correct. val is probably Nothing that's why the first code never returns "selected"
3

When you call If Not String.IsNullOrEmpty(val) Then, you're checking to see if the value is equal to String.Empty or if the value is equal to Nothing.

This would be more like writing your first example as:

Protected Function SelectedType(ByVal val As String) As String
    If val <> Nothing And val <> String.Empty Then 
        Return "selected"
    End If
End Function

Comments

1

IsNullOrEmpty offers additional security against null values, where otherwise your code would fail

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.