26

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?

Randy Minder
  • 47,200
  • 49
  • 204
  • 358

2 Answers2

28

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.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 8
    One 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
3

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");
Community
  • 1
  • 1
Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100
  • 3
    But 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