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?
2 Answers
Use an extension method if any of the following conditions are true:
- You need a method on a type and you don't own the source.
- You need a method on a type, you do own the source, and the type is an interface.
- You need a method on a type, you do own the source, but adding the method creates undesired coupling.*
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.

- 344,730
- 71
- 640
- 635
-
8One other case i would add: You need a method on a type, you own the source but the method would otherwise create a coupling that is not desired. – JaredPar Jan 18 '11 at 18:01
-
The suggested reading link is dead, I was not able to find a substitute. – Timo Feb 24 '21 at 12:09
Try this Stackoverflow post for a discussion about extension method best practices.
From my perspective I use extension methods when I have a lot of utility functions for a particular type.
I find that...
string.ExtensionMethod();
looks cleaner than...
StringHelper.ExtensionMethod("string to do something with");

- 1
- 1

- 12,977
- 6
- 62
- 100
-
3But not when you weren't the person who wrote ```ExtensionMethod()```, and spend some time trying to find ```ExtensionMethod``` in the official C# docs only to realize that you were looking in the wrong place. – Adam Parkin Jan 30 '15 at 16:16