Exception thrown with string function, replace in C #

The following code will throw an exception:

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

Why?

+4
source share
6 answers

This is correct in the documentation for string.Replace () . If you try to replace the "oldValue" parameter with an empty string, it throws an exception.

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

If you think about it, what are you really trying to do when you try to find an empty line in another line and replace it with something? Conceptually this makes no sense.

+8
source
 String cannot be of zero length. 

Probably explains why.

+7
source

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

It can be argued that both "" do not exist inside the line, or that there is an infinite number "" in any line.

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

+1
source

I would guess, because string.Replace () iterates over characters from 0 to its .Length. Obviously, this will simply skip the cycle, because there would be nothing to cut through, perhaps they threw an ejection from paranoia there?

0
source

OK, what do you expect?

Do you want to replace anything with nothing? What exactly do you want to do?

Say the old line was "ABC", what would you like it to be after your call to Replace ?

In this particular case, an exception is thrown by ArgumentException , and its text is that "the string cannot be zero length".

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

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

The Exceptions say:

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

or

ArgumentException if oldValue is an empty string ("").

So, everything behaves as expected.

0
source

The reason for this is that, conceptually, each line contains an infinite number of empty lines at the beginning, end and between characters. (This is why foo.IndexOf("") will always return 0 for any line foo .) Replacing the entire infinite number of empty lines with something else does not make sense as an operation.

0
source

All Articles