Introduction To Extension Method In C#

The extension method concept allows you to extend/add new methods in the existing class from outside class without modifying the source code.
Extension methods are a special kind of static method but they are called as if they were instance methods on the instance type. There is no difference between calling an extension method and the method they are actually defined. It is introduced in C# 3.0.
So let's look at an example of implementing extension methods
First we create a Class named Program, then we create a string and add this code to Program class. Here we want to change the first letter of the string to upper case.
  1. namespace Extensionmthd {  
  2.     class Program {  
  3.         static void Main() {  
  4.             string strName = "welcome to Dot Net Learning";  
  5.             Console.WriteLine(strName);  
  6.         }  
  7.     }  
  8. }   
Now we add a one more class name as StringHelper.cs
Extension Method in C#
In this Stringhelper class, we add the below code.
In this code we create one method and name it ChangeFirstLetterCase and pass one input parameter of type string. When we write logic here we are basically converting input string into a character array and then we are taking the first character from that array and then we are checking is it in uppercase using IsUpper function. This function is going to return true or false. If it is true then convert that letter to lower case using ToLower function otherwise if it is not upper then it is in lower case if thats the case convert it to upper case.
  1. namespace Extensionmthd {  
  2.     public static class StringHelper {  
  3.         public static string ChangeFirstLetterCase(this string inputstring) {  
  4.             if (inputstring.Length > 0) {  
  5.                 char[] charArray = inputstring.ToCharArray();  
  6.                 charArray[0] = char.IsUpper(charArray[0]) ? char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);  
  7.                 return new string(charArray);  
  8.             }  
  9.             return inputstring;  
  10.         }  
  11.     }  
  12. }  
Now we modify the Program class and we add the method ChangeFirstLetterCase().Look at that IntelliSense shows up that method with a different symbol, you have downward pointing arrow so that what indicates that this is an extension method whereas ToCharArray is a regular instance method which is defined within the string class.
Extension Method in C#
  1. namespace Extensionmthdprog {  
  2.     class Program {  
  3.         static void Main() {  
  4.             string strName = "welcome to Dot Net learning";  
  5.             string result = strName.ChangeFirstLetterCase();  
  6.             Console.WriteLine(result);  
  7.         }  
  8.     }  
  9. }  
Extension Method in C#