Extension methods enable us to "add" methods to existing types so that they could be called as an instance method, this means, there's no difference between calling an extension method and the methods defined in the original type, in short, we can say that Extension methods help us to add methods to an existing class without creating a new derived type, recompiling, or otherwise modifying them. Extension methods are static methods, but they're called as if they were instance or original methods on the extended type. For client code written in C#, F#, and Visual Basic, there is no difference between an extension method and an instance method.
Let's understand the extension method with an example. Think about the String class, the String class is defined in the .Net framework under the System namespace. The String class contains various methods like Compare() method,Concat() method , Replace() method, ToUpper() method , ToLower() method and a lots of other cool methods.
But for some reason suppose you want to add some more methods to the String class, here things become complicated, as String class is a .Net defined class so you can't touch this, It's not as easy as opening a class file and start adding a new method to it, the next option is to create a Base class with the method you want and inherit the String class from your Base class, but it is also not possible, because string Class is not our defined. The third option is to create a wrapper class as shown below.
public class StringHelper
{
public static string RemoveVowels(string str)
{
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
List<char> al = vowels.OfType<char>().ToList(); ;
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.Length; i++)
{
if (al.Contains(sb[i]))
{
sb.Replace(sb[i].ToString(), "");
i--;
}
}
return sb.ToString();
}
}
public class Program
{
public static void Main()
{
string str = @"My name is sachin kumar singh";
Console.WriteLine("With vowels---"+ str);
Console.WriteLine("without vowels----"+StringHelper.RemoveVowels(str));
Console.ReadLine();
}
}
This method works perfect but still we are not able to call the method directly from an string instance , because theRemoveVowels method is not an instance (original) method of string class so we can't do something as shown below
string str="My name is sachin";
str.RemoveVowels() // not possible.
This is where we need to create an extension method. To create an Extension method you just need to follow three steps.
Step 1. Mark the class as static.
Step 2. Mark the method as static.
Step 3. Make the type (in our case string) which you want to extend the first parameter of the method and add this keyword before it.
public static class StringHelper // first step:- make the class static
{
// second step:- make the method static
public static string RemoveVowels(this string str) //third step :- use this
{ //keyword with the type you are extending
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
List<char> al = vowels.OfType<char>().ToList(); ;
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.Length; i++)
{
if (al.Contains(sb[i]))
{
sb.Replace(sb[i].ToString(), "");
i--;
}
}
return sb.ToString();
}
}
And , now we can use the method as an instance method of string class as shown below
public class Program
{
public static void Main()
{
string str = @"My name is sachin kumar singh";
string withoutVowel = str.RemoveVowels(); // notice here
Console.WriteLine(withoutVowel);
Console.ReadLine();
}
}
You must be wondering why are we discussing Extension methods in a Linq tutorial , it is because almost all LINQ standard query operators are extension methods that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. Means Linq operators are extension methods on IEnumarable type . For example the Generic List<T> class doesn't have the Where() method , but still we are able to use Where() method as an instance method with a List type, as shown below
List<int> nums= new List<int>{1,2,3,4,5,6,7,8,9,10};
var evenNums= nums.Where(x=>x%2==0);
We are able to use Where() method on List<T> because the generic List<T> class implements the IEnumerable and Where() method is an Extension method on IEnumerable type.