When do you use extension methods, ext. methods vs. inheritance?

Times to use extension methods:

  • when you don’t control the types being extended
  • where you don’t want to force the implementor to provide code that can be done using the existing methods

For an example of the second point; you might have an extension method on IList<T> (for example, Sort) that can be written entirely using the existing IList<T> members… so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide much more functionality without breaking anything.

Times to not use extension methods:

  • when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
  • when you need access to private/protected members

Leave a Comment