Disadvantages of extension methods?
- The way that extension methods are imported (i.e. a whole namespace at a time) isn't granular. You can't import one extension from a namespace without getting all the rest.
- It's not immediately obvious from the source code where the method is defined. This is also an advantage - it means you can make your code look consistent with the rest of the methods on the type, even if you can't put it in the same place for whatever reason. In other words, the code is simpler to understand at a high level, but more complicated in terms of exactly what's being executed. I'd argue this is true of LINQ in general, too.
- You can only have extension methods, not properties, indexers, operators, constructors etc.
- If you're extending a 3rd party class and in a later version they introduce a new method with the same signature, you won't easily know that the meaning of your calling code has changed. If the new method is very similar to your extension, but with subtly different boundary conditions (or whatever) then this could lead to some very tricky bugs. It's relatively unlikely to happen though.
Extension methods are fun, but there are potential problems with them. For instance, what if you write an extension method and another library creates an extension method with the same signature? You will end up with difficulties in using both namespaces.
Also, it can be argued that they are less discoverable. I think it depends on this one. In some cases your code should be wrapped up in a class, in other cases it's fine to add that functionality as an extension method.
I generally make extension methods as wrappers to my own classes or BCL classes, and put them in a different name space. e.g. Utils and Utils.Extensions. That way the extesions don't have to be used.
Couple of things:
- It's not always clear as to where the extension method comes from unless you are inside VS.NET
- Extension methods can't be resolved via reflection or C# 4.0's dynamic lookup