An extremely simple way to make sure a null string will not throw an exception when calling a string function.

By Ken Fitzpatrick

As most VB.Net programmers have learned, when calling a string function (replace, tolower, etc...) with a null string throws an exception. The easiest way I have found to make sure this doesn't bite you, is to append the string with a "" (two double quotes) (equivelent to string.Empty). The code examples below illustrate this what throws an exception if the string is null (nothing) and the easy way to prevent it.

'Throws exception if inStr is null:
inStr.replace("1", "A")
'Does not throw an error:
(inStr & "").replace("1","A")

'Throws exception
inStr.tolower()
Does not throw exception:
(inStr & "").tolower

An extremely simple way to make sure a null string will not throw an exception when calling a string function.  (672 Views)