Friday, October 28, 2022

[FIXED] How to discriminate between null and zero length string in .NET?

Issue

What is the most efficient way to discriminate between empty and null value? I want to:

  1. evaluate CStr(str) to True when str="", whereas
  2. evaluate CStr(str) to False when str=Nothing

Solution

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%)



Answered By - anefeletos
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.