Extension methods were introduced in C# (3.0). By using extension methods we can add methods to existing types with new functionality without the need of creating new derived types.
There are a few things to remember while creating an extension method,
- The extension method should be a static method.
- Since it is a static method it should be in a static class.
- “this” keyword is used as a parameter in the extension method.
All these of three conditions should be met to create an extension method. The extension method created is visible in the C# intellisense.
Let us see an example of the extension method. Write the following code in the Program.cs.
- public static class ExtensionMethod
- {
- public static string ConvertTexttoUppercase(this string text)
- {
- return text.ToUpper();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- string text = "welcome to .net snippets!!";
- text = text.ConvertTexttoUppercase();
- Console.WriteLine(text);
- Console.ReadLine();
- }
- }
In the preceding example we have a static class “ExtensionMethod”. This class has a static function that accepts a parameter having “this” keyword. We can now use this function on a string, since we have defined the parameter as a string.
In the example we have a string with some text assigned. Our requirement is to convert the string to uppercase. So we have used this extension method on the string. When we write text and press dot we get the method in the intelligence on the string object. Refer to the following image.
When the program has run we get the following output.
Just to make sure this keyword is important for extension method to work, let us remove the “this” keyword” and check what happens. Remove the keyword and build the program. We get the below error in the program.
So it is important to use the “this” keyword as a parameter.