What is the most efficient way to discriminate between empty and null value? I want to:
- evaluate
CStr(str)
toTrue
whenstr=""
, whereas - evaluate
CStr(str)
toFalse
whenstr=Nothing
What is the most efficient way to discriminate between empty and null value? I want to:
CStr(str)
to True
when str=""
, whereasCStr(str)
to False
when str=Nothing
The HasValue
property is for nullable value types. For reference types (String
is a reference type, as are all classes) you simply compare to Nothing
:
If myString Is Nothing Then
Note the use of the Is
operator. That is for reference equality, while the =
operator is for value equality. Most types only support one or the other but String
is one of the few types that support both because they both make sense. Try this to see how they each behave:
Dim nullString As String = Nothing
Dim emptyString As String = String.Empty
If nullString Is Nothing Then
Console.WriteLine("nullString Is Nothing")
End If
If nullString = Nothing Then
Console.WriteLine("nullString = Nothing")
End If
If nullString Is String.Empty Then
Console.WriteLine("nullString Is String.Empty")
End If
If nullString = String.Empty Then
Console.WriteLine("nullString = String.Empty")
End If
If emptyString Is Nothing Then
Console.WriteLine("emptyString Is Nothing")
End If
If emptyString = Nothing Then
Console.WriteLine("emptyString = Nothing")
End If
If emptyString Is String.Empty Then
Console.WriteLine("emptyString Is String.Empty")
End If
If emptyString = String.Empty Then
Console.WriteLine("emptyString = String.Empty")
End If
Reference equality checks whether two references refer to the same object, while value equality checks whether two values are equivalent, regardless of what object they are. Nothing
and String.Empty
are not the same thing in the context of reference equality because one is an object and one is no object, but they are considered equivalent in the context of value equality.
Here it is:
<Runtime.CompilerServices.Extension>
Public Function HasValue(s As String)
Return TypeOf (s) Is String
End Function
Slightly Better equivalent: (from answer of jmcilhinney)
<Runtime.CompilerServices.Extension>
Public Function HasValue(s As String)
Return s IsNot Nothing
End Function
Also a benchmark of various methods on 10000 strings of various length:
Function(x As String)..............:Total Time (rel Efficency %)
TypeName(x) = "String".....................:0.850ms (17.1%)
VarType(x) = VariantType.String........:0.590ms (24.6%)
TypeOf (x) Is String........................... :0.150ms (96.7%)
x IsNot Nothing................................. :0.145ms (100%)