Right, so MS introduces Extension Methods for C# 3.0. Basically, it allows you to add new methods to an existing classes without having to subclass from it or change its implementation. Immediately alarm bells go off in my mind.
1) You start implementing your own extension methods for a library or standard library classes. Now it is not standardized anymore.
2) In OOP, you define a new type either through inheritance or composition. What actually is extension methods then? Likewise, in using extension methods there is no explicit relationship defined.
3) Are extension methods portable between projects? What if two extension methods for a method exists?
So are extension methods a whole bunch of worms worth avoiding? I can see that there are merits in it, as in you type less, but somehow it looks like would lead to bad practice.
Opinions?
Extension methods are not added to a type. They are just syntactic sugar. You can’t access private stuff. An extension method is just like any static method that consumes a type.
Worst thing they can do is to harm readability and mislead people. Beyond the syntax, they are nonexistent.
UPDATE (re comment):
This is exactly what I meant from "misleading people" and "harming readability." Fortunately, Visual Studio is pretty helpful in distinguishing extension methods (using an icon in the IntelliSense list and the tooltip). Personally, I’m a little biased against adding a bunch of extension methods to arbitrary classes of the framework (with the exception of
sealedclasses where extension methods can make a lot of sense) unless they provide a significant benefit for the particular project. I prefer keeping extension methods mostly for interfaces and classes on top levels of inheritance hierarchy. This will make developers only use them where they are applicable to many cases in the framework rather than making any utility method an extension (IMO, this is direct artifact of autodiscovery of extension methods in a whole namespace. I really wish C# required you to add ausingdirective on a the specificclassrather than automatically importing all extensions in anamespace).In my experience, if you don’t overuse extension methods by making every utility method that’s used a few times (I’ve seen some people do this) an extension, it’s rarely a maintenance problem. It will improve readability if used wisely.
Cluttering up classes with extension methods is not a good thing. At the extreme cases, it can be dangerous. One might introduce a name collision issue by adding a method to class with the same name of an already existing extension. This can break code snippets that previously called the extension and are now calling the new method.
In my opinion, this is the biggest issue associated to extension methods. This makes good naming of extensions very important.