Understanding Extension Methods in .Net
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
The below points describe the structure of an extension method and how it should be defined:
-
An extension method must be defined in a
static
and a non-generic class. -
An extension method must be defined as
static
. -
This first parameter of an extension method must be prefixed with the keyword
this
-
An extension method must include at least one argument with which it must be identical to the type of the class that it will be extending. (I.e. if you are writing an extension method within the String type, then the first parameter in that extension method must be of type String).
-
An extension method can be either
void
or have a return type. -
To use the extension method, you must import the namespace under which the extension method is defined.
-
You can use the extension method to overload existing methods.
-
Extension methods do accept generic types.
There are 2 important notes regarding the extension methods:
- You cannot define an extension property, field, or event.
- Extension methods cannot be used to override existing methods.