Extension Methods


What are Extension Methods?

Extension methods are special kind of static methods in a static class which enables us to add new methods to built-in types and custom types without creating new derived type.



How to implement Extension Methods:

  • Create a static method in a static class
  • Pass the type which you want to extend, as a first parameter to method
  • The first parameter should have the combination with keyword ‘this’ and ‘type’

The typical example of extension method looks like:

//Extending integer typepublic static int GetSumOfX(this int i)
{
   return i * (i + 1) / 2;
}

In the above example, keyword ‘this’ determines to which type the extension method belongs. And ‘this’ keyword is must be a first parameter to extension method.

Extension Method

In the above example you can find ‘int’ type is extended with one more new method ‘GetSumOfX’. Similarly you can extend custom types too.

Microsoft has implemented many extension methods which are integrated as part of .NET Framework. One of the best known example for this, using IEnumerable objects. When you are working with LINQ objects, these objects has the build in methods called First<>, FirstOrDefault<>, GroupBy<>, OrderBy<>, etc. All these are the extension methods of IEnumerable object.

In the below sample codes, you can find out extending both built-in types and custom types:

public static class MyExtensions
{
   //Extending integer type   public static int GetSumOfX(this int i)
   {
      return i * (i + 1) / 2;
   }   //Extending string type   public static int GetTotalWords(this string s)
   {
      return s.Split(‘ ‘).Length;
   }   //Extending Employee type   public static string GetFullName(this Employee e)
   {
      return e.GetFirstName() + ” ” + e.GetLastName();
   }
}public class Employee
{
   public string GetFirstName()
   {
      return “Srinivasa Rao”;
   }   public string GetLastName()
   {
      return “Dhulipalla”;
   }
} //Page_Load//Form_Loadint num = 100;
int totalSum =num.GetSumOfX(); //returns 5050 string sentence = “This is a string data type”;
int totalWords = sentence.GetTotalWords(); //returns 6 Employee emp = new Employee();string fullName = emp.GetFullName(); //returns firstName+lastName

In the above sample code,  int type is extended with a new method to get the sum of N numbers and string type is extended with a new method to get number of words in a string. And also a custom type called Employee class is extended with a new method to get full name of employee.

Hope this helps you understanding extension methods in C#.