Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
Extension methods can be used in any type of projects like ASP.Net, MVC, Windows Forms, and WPF etc.
Create a class with some desired name and place it in any place of the project. Make sure the namespace of the class should be the root namespace of the project. Create a static method which a return type and a parameter. The parameter should be prefixed with “this” keyword.
If any variable that matches with the parameter type of the extension can use the extension methods. Intelligence will invoke the list of extension methods implemented with that variable type.
This example is done in an MVC project.
Create a class with name “ExtensionMethods” as below and place it in the root of the project or in any folder.
public static class ExtensionMethods
public static bool IsValid(this string str)
Now extension method is created with the name “IsValid”, return type as “bool” and parameter type as string. This extension will return true if the parameter contains the string “john” or it will return false.
For using the above extension method, go to a controller; create a string with some content. Now if we want to check if the string contains the phrase “john”, it’s enough to call the method as below.
string name = "John Player";
This is the way of calling the extension method.
Extension methods are very improvement for creating common validations and string formations for a project.