What is Extension Method?
Extension methods allow developers to add new methods to the public contract of an existing type, without having to sub-class it or recompile the original type. It allows static methods to be invoked on instance variables. Extension methods can be defined on classes, structures and interfaces.
These methods must take at least one parameter, which represents the instance the method is to operate on. For example, in C#, this is done by using the modifier on such a parameter, when defining the method:
public static bool IsPalindrome(this string s)
{
//implementation follows here
}
This example allows one to write, for example:
“some string”.IsPalindrome();
Advantages:
- Cleaner and readable code. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them.
- Extend functionality on third party objects and sealed classes.
- Intellisense support. When you add an extension method M on type T, you get 'M' in T's intellisense list (assuming the extension class is in-scope). This make 'M' much easier to find than StaticClass.M(T,...)
- Create default functionality for interfaces without having to implement an abstract class
Disadvantage:
- There's no compiler error or warning if you have a regular method and an extension method with the same signature in the context.
- Object and the extension method are versioned independently. You can be put in a trouble when vendor of a class you are extending on creates the method with the same name.
- You have an extension method and another library creates an extension method with the same signature? You will end up with difficulties in using both namespaces.
- You can only have extension methods, not properties, indexers, operators, constructors etc.
Best practice:
- Put extension methods into their own namespace. By putting extension methods into their own namespace you enable consumers to include or exclude them separately from the rest of your library. This makes them pluggable.
- Avoid defining extension methods on System.Object, unless absolutely necessary. When doing so, be aware that VB users will not be able to use thus-defined extension.
- Think twice before extending types you don't own. The types can include methods with the same name any time.
- Avoid redefining extension methods on a type T with extension methods on the same type.
- Use extension methods :
- To provide helper functionality relevant to every implementation of an interface.
- To provide extension to a library that cannot be extended in other way and on which you do not have access over
- To use with Interfaces. Interfaces cannot include behavior by default. But now you can add it with Extension Methods
e08f5e29-4281-4ff3-9752-6dcdcebaed57|2|5.0
.Net, c#
Extension Methods, C#, .Net