I have been using C# extension methods for a while now and I find them to be really handy. However I am not really sure of what is the most ideal situation to use them, I feel at times I abuse them. When would you recommend the use of extension methods ?
-
2I think of extension methods as a place when you are not adding to the behavior of the class, since by definition an extension method can only make use of public fields/properties/methods on the class itself. – Rich Mar 03 '13 at 17:33
1 Answers
IMO when either it's really an extension (and not a core/critical operation), or when it's a shortcut.
An example of an extension:
Often in sandbox applications (but it could also be used in real ones, of course) is extending IEnumerable
with a Print
method.
The print method shouldn't be there (that is: it shouldn't be a part of the IEnumerable
class), but it's helping and making the syntax easier and cleaner. Also, you probably wouldn't want to ship a library with it as a part of that class.
An example of a shortcut:
Another thing I find myself often creating is an helper extension for objects with containers. Instead of calling Items.Add
and similar, I just make an AddItem
extension-method.
Something to consider is that it's just syntactic sugar, that is, it's for the you - the developer. So for .NET types and such use it when you think it's a good idea and will make things cleaner.
When it comes to "Should this method be an extension or a member?" see the first sentence in this answer, and also look here & here for more information.

- 1
- 1

- 20,711
- 12
- 68
- 90