Extension Methods in C#

Introduction

Extension methods are a special type of methods that were introduced in C# 3.0. They are used to extend the functionality of any existing type in .Net. Using extension methods we can add new methods to a class/type without modifying the original source code of the type then recompiling or creating a new derived type.

Normally, when we use LINQ standard query operators they add query functionality to the existing IEnumerable and System.Collections.Generic.IEnumerable<T> types. For using the standard query operators, first bring them in scope by writing using System.LINQ in the code file.

Now you can call for example GroupBy, OrderBy, and so on like instance methods on any type that implement IEnumerable<T>.

According to the 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 special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Syntax

As extension method is a special method, it is defined a little differently than the normal method. Here is the points to be noted when writing the extension method:

  • It should be a static method.

  • It should be written in a static class.

  • Its first parameter starts with the "this" keyword followed by a type parameter.

  • An extension method should be in the same namespace, otherwise you will need to include the namespace of the class with a using statement.

Simple Example

We can write extension methods for any existing type in our code. Most of the time we will write an extension method for types that we cannot modify that are built-in the .NET Framework.

I will make a simple extension method on string type to convert a string to an integer.

  1. public static class StringExtensions   
  2. {  
  3.     public static int ToInt32(this string value)   
  4.     {  
  5.         int result;  
  6.         if (int.TryParse(value, out result))   
  7.         {  
  8.             return result;  
  9.         }  
  10.   
  11.         return 0;  
  12.     }  
  13. }  
And now we can use it to convert a string to an integer if the string contains a numeric value. We can call it as in the following way:
  1. public class Program   
  2. {   
  3.    public static void Main()   
  4.    {   
  5.   
  6.       Console.WriteLine("123".ToInt32());   
  7.   
  8.    }   
  9. }   
You can see the live running of the example in Fiddle.