Extension Method in C#

In C#, It is introduced in C# 3.0 the extension method concept allows you to add new methods in the existing class or in the structure without modifying the 
source code of the original type and you do not require any kind of special permission from the original type and there is no need 
to re-compile the original type.

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.

using System;  
namespace ExtensionMethodsExample  
{  
   public static class Extension  
    {  
       public static int CountWord(this string str)  
       {  
           string[] userString = str.Split(new char[] { ' ', '.', '?' },  
                                       StringSplitOptions.RemoveEmptyEntries);  
           int TotalwordCount = userString.Length;  
           return TotalwordCount;  
       }   
       public static int TotalCharWithoutSpace(this string str)  
       {  
           int totalCharWithoutSpace = 0;  
           string[] userString = str.Split(' ');  
           foreach (string stringValue in userString)  
           {  
               totalCharWithoutSpace += stringValue.Length;  
           }  
           return totalCharWithoutSpace;  
       }  
    }  
} 

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.

using System;  
namespace ExtensionMethodsExample  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            string userSentance = string.Empty;  
            int totalWords = 0;  
            int totalCharWithoutSpace = 0;  
            Console.WriteLine("Enter the word");  
            userSentance = Console.ReadLine();  
            //calling Extension Method WordCount  
            totalWords = userSentance.CountWord();  
            Console.WriteLine("Total number of words is:-"+ totalWords);  
            //calling Extension Method to count character  
            totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();  
            Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);  
            Console.ReadKey();  
        }  
    }  
}

Advantage:-

It can also work with sealed class.
You can add new methods in the existing class without modifying the source code of the existing class.
The main advantage of the extension method is to add new methods in the existing class without using inheritance.

Working fine....

2020-01-15