You can switch the alarm bells off. Extension methods make only a very tiny difference to the syntax, and nothing else. Instead of writing:
SomeClass.SomeStaticMethod(someVar, someArg);
You write:
someVar.SomeStaticMethod(someArg);
It simply swaps the ordering and eliminates the class name qualifier. Otherwise, it's identical. The value of this is that you can type a variable name and the IDE can suggest useful methods to you in the intellisense feature, and you can read the code from left to right, so "nested" function calls become far more readable.
All your concerns apply equally to static methods - and are not therefore worth worrying about.
Update
Do extension methods "pretend to do magic"? Only if you think swapping some syntax around is magic!
It's more likely that you are just accustomed to seeing things written in a certain way, and so it comes as a surprise to you to see them written "backwards". But from the perspective of other languages, now it's the right way around.
Some languages allow any non-instance method to be optionally written with the first argument before the method name, and if you leave out the dot then it's a neat way of supporting infix operators like a + b
without having to do anything special.
An instance method is one way to enable this syntax, but if you were happy to do without it, then to be truly consistent, why not require instance methods to be called like this?
trimmed = string.Trim(str);
This is similar to how F# does it. After all, an instance method of string
can be viewed as having a first parameter of type string
. You don't normally think of it as a parameter, but it works much the same, and there are advantages to uniform syntax.
An instance method has access to the private members of the class it is defined in, whereas an extension method does not. But then, an instance method in a derived class does not have access to the private data of the base class. And in any case, why should the caller care about this?
Caveats
I wouldn't want to give the impression that all uses of extension methods make sense. For example, are there any good reasons to make an extension method on object
, or a generic extension method on the unconstrained type T
? Such things would be suggested by intellisense in almost any context, and would become something like language extensions, e.g. With.
Then there's the debate over whether an extension method should allow its first argument to be null
. Personally I think it's fine as long as the method's name makes this clear, so I think string.IsNullOrEmpty
would be fine as an extension method. But others are more militant about it, and I don't care, so I'd take a "when in Rome" attitude. Here's another example:
public static void DisposeIfNotNull(this IDisposable d)
{
if (d != null)
d.Dispose();
}
The name makes it clear that it incorporates a null check (that's the whole point of it).