I often get questions about the Extension Method in C#. The Extension Method was introduced in C# Version 3.0. and allows us to add functionalities in an existing class without modifying it, extending it, or re-compiling it.
Essentially, the Extension Method allows us to add a new method to an existing class:
- Without modifying it or adding code
- Without extending it or creating a new derived type
- Without recompiling the class
Extension methods are a special kind of static method but can be called on objects like an instance method. So, an extension method can be used in the same way as normal instance methods.
Steps to create an Extension Method
Step 1: Define a static visible class which will contain the Extension Method or Extension Methods. Make sure the class is visible to the client code by applying the appropriate accede modifier.
Step 2: Create a static method with at least the same visibility level as the containing class.
Step 3: The first parameter of the Extension Method always specifies the type method operates on. Make sure the type name is preceded with the “this” modifier.
Step 4: In the calling code, add the namespace that contains Extension Method class.
Step 5: Use the Extension Method on the type in the same instance method can be used. Keep in mind that we do not need to pass the first parameter because that denotes the type, however we should pass the second parameter onwards to call the extension method.
Let’s create an Extension Method!
Let us go ahead and create an Extension method for the String class. The string class does not have any WordCount method. Let us start with creating a console application project and then add a class to the console application project. We’ll name the class StringExtension.
Once the class is created, we have to perform the steps as discussed earlier:
- Make the class static and public in this case
- Add a static method
- Since the class is public, make the method public too
- Pass the first parameter of the static method as the name of the class preceded with keyword “this”
- Write the code inside method to implement functionality
namespaceExtensionMethodDemo {publicstaticclassStringExtension {publicstaticintWordCount(thisstring s) {int count = 0;for (int i = 0; i < s.Length; i++) {if (s[i] != ' ') {if ((i + 1) == s.Length) { count++; }else {if (s[i + 1] == ' ') { count++; } } } }return count; } } }
In the above code listing, we have created an Extension Method to count the number of words in a given string. You may notice that:
- The StringExtension class a public static class;
- The WordCount method is a public static method;
- The first parameter in the WordCount method is a string because we are creating WordCount as an extension method of string class;
- The first parameter type string is preceded with the keyword “this”.
Before using the Extension Method, let us compile the project. To do so, we need to perform the following steps:
- Add DLL to client project, if we have created Extension Method in different library.
- Add namespace of the Extension Method class with using directive.
- Use Extension Method as normal instance method.
We can use the newly created Extension Method as shown in the listing below:
usingSystem;namespaceExtensionMethodDemo {classProgram {staticvoidMain(string[] args) { Console.WriteLine("Enter a senetence");string inputstr = Console.ReadLine();int numberofword = inputstr.WordCount(); Console.WriteLine(numberofword); Console.ReadKey(true); } } }
As we notice in the above listing, the Extension Method WordCount is used to count the number of words in a sentence. Visual Studio also shows the Extension Methods in intellcense, by appending the word extension next to the method name as shown in the image below:
As we see, we can use an Extension Method in the same way as any instance method. There could be a scenario where we have an instance method and an Extension Method with the same name and signature. In that case, always instance method has more priority over the Extension Method. There are a few important points we should keep in mind about the Extension Method:
- It has lesser priority than the instance method, so if a class has an Extension Method and an Instance Method with the same name and signature, the instance method has priority.
- If an extension method conflicts with a member method of target type, the member method is always invoked instead of the extension method.
- The extension method can only access private members of the target type.
Extension Methods are very useful to add functionality in an existing class. Many LINQ functions are implemented as Extension Methods. I hope the information provided here will help you in your projects, and thanks for reading!