The VB6 Compatible Replace Function can return Nothing under certain conditions, possibly causing a Null Reference Exception.
VB.NET provides access to VB6 functions within the framework. While this makes the transition easier for VB programmers, you have to be careful when using these functions. The Replace() function takes three arguments - the source string, the string to replace, and the replacement string. The documentation states that if an empty string is passed as the first parameter, then an empty string is returned. This is not the case, however. The following code will fail, raising a NullReferenceException on the MsgBox line:
| Dim s As String = String.Empty s = Replace(s, "find", "replacement") MsgBox(s.Length) 'NullReferenceException |
| Dim s As String = String.Empty s = s.Replace("TEST", "") MsgBox(s.Length) 'No NullReferenceException |
| Dim s As String = String.Empty s = s.Replace("", "a") 'ArgumentException MsgBox(s.Length) |