C# – Exception thrown out with string function replace in c#

c

Following code will cause exception:

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

Why?

Best Answer

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.