This is how the Replace function in the Microsoft.VisualBasic namespace is
implemented:
Public Shared Function Replace(ByVal Expression As String, ByVal Find As
String, ByVal Replacement As String, ByVal Start As Integer = 1, ByVal
Count As Integer = -1, <OptionCompare> ByVal [Compare] As CompareMethod =
0) As String
Dim text1 As String
Try
If (Count < -1) Then
Throw New
ArgumentException(Utils.GetResourceString("Argument_GEMinusOne1",
"Count"))
End If
If (Start <= 0) Then
Throw New
ArgumentException(Utils.GetResourceString("Argument_GTZero1", "Start"))
End If
If ((Expression Is Nothing) OrElse (Start > Expression.Length)) Then
Return Nothing
End If
If (Start <> 1) Then
Expression = Expression.Substring((Start - 1))
End If
If (((Find Is Nothing) OrElse (Find.Length = 0)) OrElse (Count = 0))
Then
Return Expression
End If
If (Count = -1) Then
Count = Expression.Length
End If
text1 = Strings.Join(Strings.Split(Expression, Find, (Count + 1),
Compare), Replacement)
Catch exception1 As Exception
Throw exception1
End Try
Return text1
End Function
Note that the Expression parameter is defined as string and that the Start
parameter defaults to 1.
In your example, the test:
If ((Expression Is Nothing) OrElse (Start > Expression.Length)) Then
will be true and Nothing will be returned. If an empty string is
interpreted as Nothing then the first part will be true otherwise the
second part will be true because 1 is greater than the length of an empty
string.
So we are left with 2 scenarios:
1 - the documentation is incorrect
or
2 - whoever wrote the Replace function expects that
Nothing will be marshalled back as an empty string
Either way, the behaviour is at odds with the documentation and, yes, you
should either check to see if the result is Nothing before continuing.
If you were to use the String.Replace method instead you would avoid this
issue.
Joe HM said:
Hello -
I have the following very simple code ...
Dim lStringA As String = ""
Dim lStringB As String = ""
...
lStringB = Replace(lStringA, "DUMMY", "", Compare:=CompareMethod.Text)
lStringB.TrimEnd("\"c)
According to the documenation, Replace will return a zero-length string
("") if lStringA is zero-length. So why is lStringB Nothing and causes
an exception when calling the TrimEnd() function?
Do I have to check whether lStringA is <> "" before I call Replace()?
Thanks,
Joe