Extension Methods in C#

Introduction

According to MSDN, “Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.”

Extension methods are a unique kind of static method, as they are called as an instance method on the extended type.

Implementation

To implement extension methods, let’s work with an example of string class.

For example, we want to add a method to the string class (ChangeLetterCase) which will be used to change the case of first letter of a string to either upper or lower based on the current case.

To be able call this function as an extension method as shown below:

string newString=strFirstName.ChangeLetterCase();

Writing logic for this method in the string class is not possible as string is an existing type and we cannot make modifications to the string class as we don’t own the string class (it belongs to the .NET framework) so we do not have permission to modify it.

So to add a method to the existing string class, we can create a wrapper/helper class

Create a new class and name it “StrHelper.cs” as follows:

public class StrHelper
{
     public static string ChangeLetterCase(string strFirstName)
     {
          if(strFirstName.length > 0)
          {
               char[] charArray=strFirstName.ToCharArray();
               charArray[0]=char.IsUpper(charArray[0]) ?
                   char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
               return new string(charArray);
           }
           return strFirstName;
      }
}

To call this method we make use of

string newString=StrHelper.ChangeLetterCase(strFirstName);

But to call the method as

string newString=strFirstName.ChangeLetterCase();

We will make the following changes to our helper class:

  1. We will make the StrHelper class as static
  2. The type that the method extends (strFirstName in our case) will be passed with this keyword as the first parameter

After we make these two changes, our code will look as follows:

public static class StrHelper
{
     public static string ChangeLetterCase(this string strFirstName)
     {
          if(strFirstName.length > 0)
          {
               char[] charArray=strFirstName.ToCharArray();
               charArray[0]=char.IsUpper(charArray[0]) ?
                   char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
               return new string(charArray);
           }
           return strFirstName;
      }
}

With this, we will be able to call the extension method as our requirement.

Our calling code will be as follows:

class Demo
{
  static void Main()
  {
    string strFirstName=”codeHubs”;
    string newString=strFirstName.ChangeLetterCase(strFirstName);
    //We can always call the method as follows:
    //string newString=StringHelper.ChangeLetterCase(strFirstName);
    Console.WriteLine(newString);
  }
}

Extension methods are used to make life of a developer easy. If we observe, we will see that the extension method we created will be shown in intellisense but will have a different visual representation (with a down blue arrow)

Advantages of Extension methods:

  1. Extension methods allows us to add functionalities to existing classes without making changes to the source code of the class or using inheritance
  2. Extension methods can also work with sealed class

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories