Parameter | Details |
---|---|
this | The first parameter of an extension method should always be preceded by the this keyword, followed by the identifier with which to refer to the "current" instance of the object you are extending |
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.
Which namespace?
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 Foo
.
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 System.Linq
namespace.
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?
Applicability
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
.
after a type instance, then it comes in VS intellisense.