Reputation: 7122
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
Upvotes: 3
Views: 2217
Reputation: 16232
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 ()
Upvotes: 4
Reputation: 564831
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
Upvotes: 3
Reputation: 29000
IsNullOrEmpty offers additional security against null values, where otherwise your code would fail
Upvotes: 1