Why does the string Remove() method allow a char as a parameter?

user1968030 picture user1968030 · Oct 13, 2013 · Viewed 13k times · Source

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?

enter image description here

Why does the compiler have this behavior?

Answer

MichaC picture MichaC · Oct 13, 2013

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!