I would like to support the other answers here that mention improved code readability as an important reason behind extension methods. I'll demonstrate this with two aspects of this: method chaining vs. nested method calls, and cluttering of a LINQ query with meaningless static class names.
Let's take this LINQ query as an example:
numbers.Where(x => x > 0).Select(x => -x)
Both Where
and Select
are extension methods, defined in the static class Enumerable
. Thus, if extension methods didn't exist, and these were normal static methods, the last line of code would essentially have to look like this:
Enumerable.Select(Enumerable.Where(numbers, x => x > 0), x => -x)
See how much nastier that query just got.
Second, if you now wanted to introduce your own query operator, you would naturally have no way of defining it inside the Enumerable
static class, like all the other standard query operators, because Enumerable
is in the framework and you have no control over that class. Therefore, you'd have to define your own static class containing extension methods. You might then get queries such as this one:
Enumerable.Select(MyEnumerableExtensions.RemoveNegativeNumbers(numbers), x => -x)
// ^^^^^^^^^^^^^^^^^^^^^^
// different class name that has zero informational value
// and, as with 'Enumerable.xxxxxx', only obstructs the
// query's actual meaning.