Extension Method In C#

Extension Methods are a new feature in C# 3.0. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in .NET. An Extension Method is a static method to the existing static class. We call an Extension Method in the same general way; there is no difference in calling.

An Extension Method is:

  1. It is a static method.
  2. It must be located in a static class.
  3. It uses the "this" keyword as the first parameter with a type in .Net and this method will called by a given type instance on the client side.
  4. It also shown by VS intellisense. When we press the dot (.) after a type instance then it comes in VS intellisense.
  5. An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  6. You can give any name of for the class that has an Extension Method but the class should be static.
  7. If you want to add new methods to a type and you don't have the source code for it then the solution is to use and implement Extension Methods of that type.
  8. If you create Extension Methods that have the same signature methods as the type you are extending then the Extension Methods will never be called. 

We create an Extension Method for a string type so string will be specified as a parameter for this Extension Method and that method will be called by a string instance using the dot operator. 

extension-01.png

In the above method WordCount(), we are passing a string type with this so it will be called by the string type variable, in other words a string instance.

Now we create a static class and two static methods, one for the total word count in a string and another for the total number of characters in a string without a space.

  1. using System;  
  2. namespace ExtensionMethodsExample  
  3. {  
  4.    public static class Extension  
  5.     {  
  6.        public static int WordCount(this string str)  
  7.        {  
  8.            string[] userString = str.Split(new char[] { ' ''.''?' },  
  9.                                        StringSplitOptions.RemoveEmptyEntries);  
  10.            int wordCount = userString.Length;  
  11.            return wordCount;  
  12.        }   
  13.        public static int TotalCharWithoutSpace(this string str)  
  14.        {  
  15.            int totalCharWithoutSpace = 0;  
  16.            string[] userString = str.Split(' ');  
  17.            foreach (string stringValue in userString)  
  18.            {  
  19.                totalCharWithoutSpace += stringValue.Length;  
  20.            }  
  21.            return totalCharWithoutSpace;  
  22.        }  
  23.     }  
  24. }   
Now we create an executable program that has a string as an input and uses an Extension Method to count the total words in that string and the total number of characters in that string then show the result in a console screen.
  1. using System;  
  2. namespace ExtensionMethodsExample  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             string userSentance = string.Empty;  
  9.             int totalWords = 0;  
  10.             int totalCharWithoutSpace = 0;  
  11.             Console.WriteLine("Enter the your sentance");  
  12.             userSentance = Console.ReadLine();  
  13.             //calling Extension Method WordCount  
  14.             totalWords = userSentance.WordCount();  
  15.             Console.WriteLine("Total number of words is :"+ totalWords);  
  16.             //calling Extension Method to count character  
  17.             totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();  
  18.             Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);  
  19.             Console.ReadKey();  
  20.         }  
  21.     }  
  22. }
extension-02.PNG


Similar Articles