5

Following code will cause exception:

string IDs = "";
IDs = IDs.Replace("", "");

Why?

6 Answers 6

8

It's right in the documentation for string.Replace(). If you try to replace with the "oldValue" parameter as an empty string, it throws an exception.

Exception                  Condition
ArgumentException          oldValue is the empty string (""). 

If you think about it, what are you actually trying to do when you try to find an empty string in another string and replace it with something? Conceptually it doesn't make sense.

Sign up to request clarification or add additional context in comments.

1 Comment

>>What are you trying to do? This comes up when you use a dynamic string as the string to find. I remember I ran into this issue once when building up log messages that redacted passwords. For example, log(ConnectString.Replace(pw, "***")) If the password was blank, my Replace would blow up, so I ended up creating a "Safe Replace" function that harmlessly returned the original string if the find string was null or blank.
7
String cannot be of zero length.

Probably explains why.

Comments

1

It throws an exception because "" would never be found.

It can be argued that both "" does not exist within a string, or that there are an infinite number of "" within any string.

It just plain don't make sense to replace an empty string with an empty string.

Comments

1

Well, what do you expect?

You want to replace nothing with nothing? What exactly do you want to do?

Let's say the old string was "ABC", what would you want it to be after your call to Replace?

In this particular case, the exception thrown is an ArgumentException, and the text of it is that "String cannot be of zero length".

So, the criteria of calling the .Replace method is that what you want to replace is not a string without contents.

Let's check the documentation of String.Replace(String, String):

Under Exceptions it says:

ArgumentNullException, if oldValue is a null reference (Nothing in Visual Basic).

or

ArgumentException, if oldValue is the empty string ("").

So everything is behaving like expected.

Comments

1

The reason for this is that conceptually, every string contains an infinite number of empty strings at the start, at the end, and between characters. (This is why foo.IndexOf("") will always return 0 for any string foo.) Replacing all the infinite amount of empty strings with something else makes no sense as an operation.

Comments

0

I'd guess it's because string.Replace() loops through characters from 0 to its .Length. Obviously this would just skip the loop as there would be nothing to loop through, perhaps they threw a throw in there out of paranoia?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.