Can someone explain me why this string extended method gives me an ArgumentOutOfRangeException (Index and count must refer to a location within the string. Parameter name: count),

public static string Remove(this string str, char lower, char upper)
        return str.Where(ch => ch <= upper && ch >=lower)
                       .Aggregate(string.Empty, (current, ch) => current + ch);

while a method does not.

private string Remove(string str, char lower, char upper)
        return str.Where(ch => ch <= upper && ch >= lower)
                       .Aggregate(string.Empty, (current, ch) => current + ch);

When you're calling your extension method, you would call it in such a manner as

string newString = someString.Remove(a, b); // where a and b are characters

A couple of points to consider:

1) System.String already has a Remove method that accepts two parameters of type int.
2) char values are implicitly convertible to integers.

When it comes down to static/instance methods versus extension methods, the member method will win out every time.

See: "An extension method will never be called if it has the same signature as a method defined in the type."

So the error you're seeing has nothing at all to do with the code inside of your extension method, it's that your arguments are causing the instance method that is actually being called to fail.

This is why you want to be cautious when deciding to use an extension method. If you have access to the code of the type, it is better to simply change the code of the type rather than define an extension method somewhere else. If it is a framework type (such as int, string, etc.) or a type from a third party compiled library, you have to consider that in a future release they could define a method matching your extension, in which case your existing code would not perform as you intend.

commented: Exposure of deep knowledge. +6