KnowDotNet Visual Organizer

.NET Gotcha - VB6 Compatible Replace Function

by Les Smith and Brian Davis
Print this Article Discuss in Forums

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

It is possible that this is the result of the different ways VB6 and VB.NET handle String declaration/initialization.  In VB6, declaring a new String resulted in the String being initialized to an empty String.  This is not true in .NET.  Strings have an initial value of Nothing.  Because Strings are immutable, then the Replace function must create a new String to return.  In VB6, this would in fact return an empty String, but in VB.NET it returns Nothing.  To avoid this, you can use the Replace() function of the String class.

   Dim s As String = String.Empty
   s = s.Replace("TEST", "")
   MsgBox(s.Length)  
'No NullReferenceException


One thing to note is that passing an empty String in the Find parameter to the Replace method will raise an Argument Exception.  

   Dim s As String = String.Empty
   s = s.Replace("", "a")  
'ArgumentException
   MsgBox(s.Length)

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing