Beware of Replace functions!

If you are using VB.NET and want to replace all occurrences of one string in a variable with another string, you can use either Replace function from Microsoft.VisualBasic namespace (which is, unfortunately, imported by default in every new VB project and you cannot even see this in the code!) or Replace function from String class (and this is a preferred method).

I was absolutely sure that the following snippets of code would give the same results:
Dim s1 As String = ""
s1 = Replace(s1, "foo", "fee")

Dim s2 As String = ""
s2 = s2.Replace("foo", "fee")
Well, they don't. While the variable s2 remains to be an empty string, s1 is set to Nothing. That's something worth remembering.

No comments:

Post a Comment