I'm having a bit of a difficult time determining when to implement a method as an extension method and when to implement a method as a stand-alone method. What are some best practices people follow in determining this?
For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
Use an extension method if any of the following conditions are true:
Otherwise, you should use a real method on the actual type itself.
I don't think it makes a whole lot of sense to create an extension method for a class or struct that you own the source for - why confuse readers with an extension method when a regular method will suffice?
Suggested reading: Framework Design Guidelines: Extension Methods
* Imagine that you wanted to add convenience methods to a type but don't want to create dependencies to assemblies or types that shouldn't be part of the API. You could use extension methods to manage this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With