Strange thing using Replace(..) in vb.net

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
in our application we use the following code snippet:

Dim target As String = Replace(txtLinkTarget.Text, "<SEP>", "'")
If target.StartsWith("(") AndAlso target.EndsWith(")") Then

In line 1 the text-value of of a textbox is retrieved. All occurences of
<SEP> are then replaced by an apostrophe.

However, if txtLinkTarget.Text returns an empty string, the Replace
function evaluates to Nothing, giving me a nice exception in line 2.
How is that possible?
 
How is that possible?

The Replace method has two Exceptions:

ArgumentNullException = original string is a null reference (Nothing in
Visual Basic).
ArgumentException = original string is an empty string ("").

http://msdn.microsoft.com/library/d...f/html/frlrfSystemStringClassReplaceTopic.asp

You need to verify that your original string is not null (Nothing) or empty
("") before calling replace.

If (Not OriginalString Is Nothing) AndAlso (Not OriginalString = "") Then

'Perform your replace and StartsWith/EndsWith here...

End If

Paul
 
Havagan,

You reference to the String.Replace while in my opinion the VB Replace is
used.

Cor
 
Thanks Paul

This is somewhat inconvinient, adding two additional lines to check if the
string is correct. What harm could an empty string do in the Replace
function. The function should be able to handle empty strings just like any
string object other than nothing.
 
Oh I thougth Havagan meant VB Replace, but I think its the same problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top