In c#, extension methods are useful to extend the behavior of existing types by adding new methods without modifying, deriving, or recompiling the original types such as class, struct, or interface.
In c#, we can implement our own extension methods for any .NET type such as custom class, .NET framework class, or third party classes.
To create an extension method, we need to define a static class and implement an extension method as a static method with the required parameters. The first parameter of the method will specify the type on which the extension method will operate, and it must be preceded by this modifier.
Following is the example of implementing an extension method for System.string class.
If you observe the above example, we are extending the behavior of string type by creating the IsValidEmail extension method.
In c#, the extension methods are same as static methods, but the only difference is, the first parameter type in the extension method must be preceded by this modifier.
We need to include the Extensions namespace in our application wherever we want to access the IsValidEmail extension method like as shown below.
After adding the namespace, we can access the extension method as an instance method of extended type like as shown below.
In c#, the extension methods will be defined as static methods of a static class, but those are accessible as an instance method of extended type.
Following is the example of accessing the IsValidEmail extension method by including the Extensions namespace.
If you observe the above example, we included the Extensions namespace in our program, and we are able to access the IsValidEmail extension method as an instance method of string extension type.
When we execute the above program, we will get the result as shown below.
In the above example, we extended the behavior of the .NET framework System.string class type. In the same way, we can extend the behavior of custom classes also based on our requirements.
While creating an extension method for a specific type, we need to ensure that the same signature method will not exist for the specified type; otherwise, the extension method will never be called.
This is how we can extend the behavior of existing types by adding new methods without modifying the original types.
The following are the important points which we need to remember about extension methods in c#.