When using extension methods, it is good to set out a convention for your project in which your team will follow. This recipe seeks to demonstrate a few best practices and conventions that should get the project to a state where it can be easily maintained and worked on by other team members.
Extensions normally go into a class library or a folder dedicated to just extension methods. The files and classes are named after the type they extend.
The following screenshot shows how a solution is usually structured after adding many more types of extensions:
There are a few practices and conventions that should guide you when using extension methods in your projects:
Own namespace: Extension methods should be in their own namespace. By making your extensions pluggable, you allow the user to include or exclude them from the rest of the library. This allows the user to remove and add their own implementation as they wish. A good convention would be to place them in a namespace, such as
MyCompany.Common.Extensions
.Be careful of extending types you do not own: Changes to types you do not own may occur and cause changes that may break your extension methods.
Prioritize extension of interfaces over classes: As a class developer, you can think of interfaces as immutable. If an interface changes, you can expect that all classes implementing from that interface will also be broken. However, this is still possible, the chances of an interface being modified are less likely.
Be specific: Extensions on less specific types are more likely to be broken by external change than extensions on more specific types. This is because the higher a type is in the hierarchy, the more types there are that derive from it. An extension method on
Object
type can be broken by the introduction of any member to any type anywhere. An extension method on string, on the other hand, can only be broken by changes to string or other extension methods.
In this recipe, you have learned a few best practices, dos and don'ts of extension methods.