What is .Net Extension Method

.Net Extension Method is one of a nice features introduced with .Net 3.0. It allows developers to add new functionalities to existing data types without having a need to inherit from these types or compile old code. For example, if you are encrypting and decrypting strings in your application, wouldn’t it nice to have a code like below
StringObject.Encrypt();
In the tradition way, we used to create a static helper method that we call and pass string to it as a parameter:

public static string Encrypt(string input)
{
//….Logic goes here
return encyptedValue;
}

Implementing Extension Methods is very easy.. All what you need to do is to create a static class and have your extension method as static method and use this keyword on the parameter list.. Below is a sample code

public static class MyExtensions {
public static string Encrypt(this string input) {
//….Logic goes here
return encyptedValue;
}
}

Note the “this” keyword that is being used on the parameter.. this what make this .Net Extension Method. You can call this method in 2 ways:
1. As extension method, str.Encrypt();
2. As regular method: MyExtensionClass.Encrypt(str);
Both syntax are equivalent to each other but the first one is less code.