Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods vs. Regular Methods - Best Practice Ideas

Tags:

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?

like image 950
Randy Minder Avatar asked Jan 18 '11 17:01

Randy Minder


People also ask

Are extension methods good practice?

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.

Why we use extension methods?

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.

What is the difference between a static method and an extension method?

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.

When should we use extension methods in C#?

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.


1 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.

like image 198
Andrew Hare Avatar answered Oct 30 '22 21:10

Andrew Hare