- public static ReturnType MyExtensionMethod(this TargetType target)
- public static ReturnType MyExtensionMethod(this TargetType target, TArg1 arg1, ...)
|this||The first parameter of an extension method should always be preceded by the |
Extension methods are syntactic sugar that allow static methods to be invoked on object instances as if they were a member of the type itself.
Extension methods require an explicit target object. You will need to use the
this keyword to access the method from within the extended type itself.
Extensions methods must be declared static, and must live in a static class.
The choice of namespace for your extension method class is a trade-off between visibility and discoverability.
The most commonly mentioned option is to have a custom namespace for your extension methods. However this will involve a communication effort so that users of your code know that the extension methods exist, and where to find them.
An alternative is to choose a namespace such that developers will discover your extension methods via Intellisense. So if you want to extend the
Foo class, it is logical to put the extension methods in the same namespace as
It is important to realise that nothing prevents you using "someone else's" namespace: Thus if you want to extend
IEnumerable, you can add your extension method in the
This is not always a good idea. For example, in one specific case, you may want to extend a common type (
bool IsApproxEqualTo(this double value, double other) for example), but not have that 'pollute' the whole of
System. In this case it is preferable to chose a local, specific, namespace.
Finally, it is also possible to put the extension methods in no namespace at all!
A good reference question: How do you manage the namespaces of your extension methods?
Care should be taken when creating extension methods to ensure that they are appropriate for all possible inputs and are not only relevant to specific situations. For example, it is possible to extend system classes such as
string, which makes your new code available to any string. If your code needs to perform domain specific logic on a domain specific string format, an extension method would not be appropriate as its presence would confuse callers working with other strings in the system.
The following list contains basic features and properties of extension methods
- It must be a static method.
- It must be located in a static class.
- It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
- It also shown by VS intellisense. When we press the dot
.after a type instance, then it comes in VS intellisense.
- An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
- You can give any name for the class that has an extension method but the class should be static.
- If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.
- If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.
Extension methods - overview
Extension methods were introduced in C# 3.0. Extension methods extend and add behavior to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. They are especially helpful when you cannot modify the source of a type you are looking to enhance. Extension methods may be created for system types, types defined by third parties, and types that you have defined yourself. The extension method can be invoked as though it were a member method of the original type. This allows for Method Chaining used to implement a Fluent Interface.
An extension method is created by adding a static method to a static class which is distinct from the original type being extended. The static class holding the extension method is often created for the sole purpose of holding extension methods.
Extension methods take a special first parameter that designates the original type being extended. This first parameter is decorated with the keyword
this (which constitutes a special and distinct use of
this in C#—it should be understood as different from the use of
this which allows referring to members of the current object instance).
In the following example, the original type being extended is the class
String has been extended by a method
Shorten(), which provides the additional functionality of shortening. The static class
StringExtensions has been created to hold the extension method. The extension method
Shorten() shows that it is an extension of
string via the specially marked first parameter. To show that the
Shorten() method extends
string, the first parameter is marked with
this. Therefore, the full signature of the first parameter is
this string text, where
string is the original type being extended and
text is the chosen parameter name.
The object passed as the first argument of an extension method (which is accompanied by the
this keyword) is the instance the extension method is called upon.
For example, when this code is executed:
The values of the arguments are as below:
Note that extension methods are only usable if they are in the same namespace as their definition, if the namespace is imported explicitly by the code using the extension method, or if the extension class is namespace-less. The .NET framework guidelines recommend putting extension classes in their own namespace. However, this may lead to discovery issues.
This results in no conflicts between the extension methods and the libraries being used, unless namespaces which might conflict are explicitly pulled in. For example LINQ Extensions:
Since C# 6.0, it is also possible to put a
using static directive to the class containing the extension methods. For example,
using static System.Linq.Enumerable;. This makes extension methods from that particular class available without bringing other types from the same namespace into scope.
When a class method with the same signature is available, the compiler prioritizes it over the extension method call. For example:
Note that if there are two extension functions with the same signature, and one of them is in the same namespace, then that one will be prioritized. On the other hand, if both of them are accessed by
using, then a compile time error will ensue with the message:
The call is ambiguous between the following methods or properties
Note that the syntactic convenience of calling an extension method via
originalTypeInstance.ExtensionMethod() is an optional convenience. The method can also be called in the traditional manner, so that the special first parameter is used as a parameter to the method.
I.e., both of the following work:
Explicitly using an extension method
Extension methods can also be used like ordinary static class methods. This way of calling an extension method is more verbose, but is necessary in some cases.
When to call extension methods as static methods
There are still scenarios where you would need to use an extension method as a static method:
- Resolving conflict with a member method. This can happen if a new version of a library introduces a new member method with the same signature. In this case, the member method will be preferred by the compiler.
- Resolving conflicts with another extension method with the same signature. This can happen if two libraries include similar extension methods and namespaces of both classes with extension methods are used in the same file.
- Passing extension method as a method group into delegate parameter.
- Doing your own binding through
- Using the extension method in the Immediate window in Visual Studio.
using static directive is used to bring static members of a static class into global scope, extension methods are skipped. Example:
If you remove the
this modifier from the first argument of the
Shorten method, the last line will compile.
Extension methods aren't supported by dynamic code.
The reason [calling extension methods from dynamic code] doesn't work is because in regular, non-dynamic code extension methods work by doing a full search of all the classes known to the compiler for a static class that has an extension method that matches. The search goes in order based on the namespace nesting and available
usingdirectives in each namespace.
That means that in order to get a dynamic extension method invocation resolved correctly, somehow the DLR has to know at runtime what all the namespace nestings and
usingdirectives were in your source code. We do not have a mechanism handy for encoding all that information into the call site. We considered inventing such a mechanism, but decided that it was too high cost and produced too much schedule risk to be worth it.
Extension methods as strongly typed wrappers
Extension methods can be used for writing strongly typed wrappers for dictionary-like objects. For example a cache,
HttpContext.Items at cetera...
This approach removes the need of using string literals as keys all over the codebase as well as the need of casting to the required type during the read operation. Overall it creates a more secure, strongly typed way of interacting with such loosely typed objects as Dictionaries.
Extension methods can only see public (or internal) members of the extended class
Extension methods are just a syntactic sugar, and are not actually members of the class they extend. This means that they cannot break encapsulation—they only have access to
public (or when implemented in the same assembly,
internal) fields, properties and methods.
Extension methods dispatch based on static type
The static (compile-time) type is used rather than the dynamic (run-time type) to match parameters.
Also the dispatch based on static type does not allow an extension method to be called on a
Extension methods for chaining
When an extension method returns a value that has the same type as its
this argument, it can be used to "chain" one or more method calls with a compatible signature. This can be useful for sealed and/or primitive types, and allows the creation of so-called "fluent" APIs if the method names read like natural human language.
Or like this
Extension methods for handling special cases
Extension methods can be used to "hide" processing of inelegant business rules that would otherwise require cluttering up a calling function with if/then statements. This is similar to and analogous to handling nulls with extension methods. For example,
Extension methods in combination with interfaces
It is very convenient to use extension methods with interfaces as implementation can be stored outside of class and all it takes to add some functionality to class is to decorate class with interface.
Extension methods on Interfaces
One useful feature of extension methods is that you can create common methods for an interface. Normally an interface cannot have shared implementations, but with extension methods they can.
In this example, the method
FeetDriven can be used on any
IVehicle. This logic in this method would apply to all
IVehicles, so it can be done this way so that there doesn't have to be a
FeetDriven in the
IVehicle definition which would be implemented the same way for all children.
Extension methods with Enumeration
Extension methods are useful for adding functionality to enumerations.
One common use is to implement a conversion method.
Now you can quickly convert your enum value to a different type. In this case a bool.
Alternatively extension methods can be used to add property like methods.
Extensions and interfaces together enable DRY code and mixin-like functionality
Extension methods enable you to simplify your interface definitions by only including core required functionality in the interface itself and allowing you to define convenience methods and overloads as extension methods. Interfaces with fewer methods are easier to implement in new classes. Keeping overloads as extensions rather than including them in the interface directly saves you from copying boilerplate code into every implementation, helping you keep your code DRY. This in fact is similar to the mixin pattern which C# does not support.
System.Linq.Enumerable’s extensions to
IEnumerable<T> is a great example of this.
IEnumerable<T> only requires the implementing class to implement two methods: generic and non-generic
System.Linq.Enumerable provides countless useful utilities as extensions enabling concise and clear consumption of
The following is a very simple interface with convenience overloads provided as extensions.
Generic Extension Methods
Just like other methods, extension methods can use generics. For example:
and calling it would be like:
Likewise for multiple Type Arguments:
Calling it would be like:
You can also create extension methods for partially bound types in multi generic types:
Calling it would be like:
You can also specify type constraints with
Extension Method Example: Comparing 2 Lists
You can use the following extension method for comparing the contents of two IList< T > instances of the same type.
By default the items are compared based on their order within the list and the items themselves, passing false to the
isOrdered parameter will compare only the items themselves regardless of their order.
For this method to work, the generic type (
T) must override both
Extension methods are static methods which behave like instance methods. However, unlike what happens when calling an instance method on a
null reference, when an extension method is called with a
null reference, it does not throw a
NullReferenceException. This can be quite useful in some scenarios.
For example, consider the following static class:
Using Extension methods to build new collection types (e.g. DictList)
You can create extension methods to improve usability for nested collections like a
Dictionary with a
Consider the following extension methods:
you can use the extension methods as follows:
Using Extension methods to create beautiful mapper classes
We can create a better mapper classes with extension methods, Suppose if i have some DTO classes like
and i need to map to corresponding view model classes
then I can create my mapper class like below
Then finally i can invoke my mapper like below
The beauty here is all the mapping method have a common name (ToViewModel) and we can reuse it several ways
Using Extension methods with Static methods and Callbacks
Consider using Extension Methods as Functions which wrap other code, here's a great example that uses both a static method and and extension method to wrap the Try Catch construct. Make your code Bullet Proof...