简体   繁体   中英

Extension Methods vs. Regular Methods - Best Practice Ideas

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?

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM