user4951
user4951

Reputation: 33138

Why Does Replace Return Nothing on Empty String

Replace("",vbLf, "")

Go figure.

It should return ""

No. It returns nothing.

Just put the code in vb.net

I think it should return "". Replace all occurance of vbLF with "". Because the original string is "" then it simply replace nothing and we got back ""

\No. We got back nothing.

Upvotes: 7

Views: 2933

Answers (3)

Jacob M.
Jacob M.

Reputation: 780

To elaborate on this for anyone winding up here, when you just call "Replace" you're getting Microsoft.VisualBasic.Replace, not the String.Replace you're expecting.

Microsoft.VisualBasic.Replace: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic?view=netframework-4.7.2

String.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.7.2

If you want to return an empty string you need to call the .Replace method of a String:

dim myString as String = ""
myString.Replace("a", "b")

This of course finds no match, but the behavior is instead to return and empty string now instead of Nothing when the input expression is an empty String.

Upvotes: 0

AdamL
AdamL

Reputation: 177

I second the original post, VB.net should not return NOTHING with its REPLACE function. However, it does if your replace happens to return Nothing if the expression is an empty string.

Upvotes: 1

Kenneth Funk
Kenneth Funk

Reputation: 396

You are using Visual Basic string functions, not .Net. The Visual Basic runtime usually evaluates Nothing as an empty string ("").

Upvotes: 3

Related Questions