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.
Modify your constructor to the following so that it calls the base class constructor properly:
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.
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.
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.