Extension methods in C#

Extension methods are special methods in C#, which allows to extend the functionality of an existing class. These methods are mostly used to add an additional behavior to classes which are closed to modification.

While programming we come across a situation where some third party library does not provide a certain behavior in their classes and we want to have the same. In such situation extension methods come to rescue.

Syntax for extension method is very simple. Extension methods are always static. First parameter in this method should be of type which you are going to extend, preceded by this keyword . (This is mandatory to make a method as extension method, though you do not have to pass it.) Other parameters can be defined after this as required.

public static ExtensionMethod(this TypeToExtend parameter)
{

//put desired stuff to be done with parameter

}

Lets have a look to real time example.

public static class ExtensionMethods
{

  public static int GetNumberCount(this String myString)
  {
    int count = 0;
    
    foreach(char character in myString)
    { 
       if(Char.IsDigit(character))
         count++;
    }

    return count;
 } 

} 

Above extension method can be invoked in the same way as instance method:

string numberedString = "Company strength is 2948";
int numberCount = numberedString.GetNumberCount();

More facts about extension methods:

  • Extension methods are always written in a static class.
  • Extension methods are always static.
  • If class which is being extended contains a method with same signature as that of the extension method, then extension method never gets called.
  • Though extension methods are static they are invoked as an instance method.
  • Multi parameter extension method can be written.

About sagar

With over 13 years of professional experience as a .NET developer, I have honed my expertise in various facets of the .NET framework and related technologies. My extensive background includes proficiency in WPF, Web APIs, WCF services, and Windows services, which has enabled me to deliver robust and scalable applications across different domains.

Leave a Reply

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