Why does the string Remove() method allow a char as a parameter?
Consider this code:
var x = "tesx".Remove('x');
If I run this code, I get this exception:
startIndex must be less than length of string.
Why can I pass a char instead of an int to this method? Why don't I get a compilation error?
Why does the compiler have this behavior?
you try to remove 'x' which is a declared as char, x is equal to 120
The .Remove
only takes 2 parameters of type int
the start and (optional) count to remove from the string.
If you pass a char, it will be converted to the integer representation. Meaning if you pass 'x' -> 120 is greater than the string's .Length
and that's why it will throw this error!
Implicit conversion
lets you compile this code since char can be converted to int and no explicit conversion is required. This will also compile and the answer will be 600 (120*5)
-
char c = 'x';
int i = c;
int j = 5;
int answer = i * j;
From MSDN, implicit conversion is summarized as below -
As other's have stated you could use Replace
or Remove
with valid inputs.
There is no overload of Remove
that takes a char
, so the character is implicitly converted to an int
and the Remove
method tries to use it as an index into the string, which is way outside the string. That's why you get that runtime error instead of a compile time error saying that the parameter type is wrong.
To use Remove
to remove part of a string, you first need to find where in the string that part is. Example:
var x = "tesx";
var x = x.Remove(x.IndexOf('x'), 1);
This will remove the first occurance of 'x'
in the string. If there could be more than one occurance, and you want to remove all, using Replace
is more efficient:
var x = "tesx".Replace("x", String.Empty);
Remove takes an int parameter for the index within the string to start removing characters, see msdn. The remove call must automatically convert the char to its ASCII integer index and try to remove the character at that index from the string, it is not trying to remove the character itself.
If you just want to remove any cases where x occurs in the string do:
"testx".Replace("x",string.Empty);
If you want to remove the first index of x in the string do:
var value = "testx1x2";
var newValue = value.Remove(value.IndexOf('x'), 1);