English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Extension Methods

As the name implies, extension methods are auxiliary methods. Extension methods allow you to inject other methods without modifying, deriving, or recompiling the original class, structure, or interface. Extension methods can be added to your own custom class, .NET Framework class, or third-party class or interface.

Definition of extension methods

Extension methods are in C# 3New features added in .0 can extend the functionality of source code through ADD File mode without modifying the source class code.

The requirements for extension methods are as follows:

  • The extension method must be included in a static-modified class.

  • The extension implementation must be in a static form.

  • The first parameter of the extension method is prefixed with this, indicating that the class object to be extended is required, and the parameter list of the extension method starts from the second parameter.

In the following example, IsGreaterThan() is an extension method of the int type, which returns true if the value of the int variable is greater than the provided integer parameter.

int i = 10;
bool result = i.IsGreaterThan(100); //Returns FALSE

The IsGreaterThan () method is not a method of the int data type (Int32 It is an extension method written by the programmer for the int data type. By including a namespace that defines the IsGreaterThan () extension, the IsGreaterThan () extension method will be available throughout the application.

 Extension methods in Visual Studio intellisense have special symbols, so you can easily distinguish between class methods and extension methods.

Extension method symbols in Visual Studio intellisense

Writing extension methods

Now let's see how to write extension methods.

LINQ is built on top of extension methods that operate on IEnumerable and IQueryable types.

Extension methods are actually a special type of static method defined in a static class. To define an extension method, first, define a static class.

For example, in the following example, we created a class IntExtensions under the ExtensionMethods namespace. The IntExtensions class will contain all extension methods applicable to the int data type. (You can use any name for the namespace and class.)

namespace ExtensionMethods
{
    public static class IntExtensions
    {
    }
}

Now, define the static method as an extension method, where the first parameter of the extension method specifies the type to which the extension method applies. We will use this extension method on the int type. Therefore, it must be prefixed withthis Modifier.

For example, the IsGreaterThan() method operates on int, so the first parameter is this int i.

namespace ExtensionMethods
{
    public static class IntExtensions
     {
        public static bool IsGreaterThan(this int i, int value)
        {
            return i > value;
        }
    }
}

Now, you can include the ExtensionMethods namespace anywhere you want to use this extension method.

Using extension methods

using ExtensionMethods;
class Program
{
    static void Main(string[] args)
    {
        int i = 10;
        bool result = i.IsGreaterThan(100); 
        Console.WriteLine(result);
    }
}
Output:
false
The only difference between regular static methods and extension methods is that the first parameter of the extension method specifies the type on which the operation will be performed, followed by this Keywords.

Summary of the principles of extension methods

  1. C# only supports extension methods, not extension properties, extension events, extension operators, and so on.

  2. Extension methods (methods before the first parameter marked with 'this') must be declared in non-generic static classes, and the extension method must have one parameter, and only the first parameter uses the 'this' marker.

  3. When the C# compiler searches for extension methods in static classes, it requires that these static classes themselves must have file scope.

  4. The C# compiler requires the 'import' of extension methods. (Static methods can be named arbitrarily, and the C# compiler needs to spend time searching for methods, checking all static classes in the file scope, and scanning all their static methods to find a match).

  5. Multiple static classes can define the same extension method.
    When an extension method extends a type, it also extends the derived types.

Extension method declaration

  • The method must be defined in a non-nested, non-generic static class (therefore, it must be a static method).

  • At least one parameter is required.

  • The first parameter must be prefixed with the this keyword.

  • The first parameter cannot have any other modifiers (such as ref or out).

  • The type of the first parameter cannot be a pointer type.

Points to Remember

  • Extension methods are other custom methods that are initially not included in the class.

  • Extension methods can be added to custom, .NET Framework, or third-party classes, structs, or interfaces.

  • The first parameter of the extension method must be the type to which the extension method is applicable, followed bythisKeywords.

  • Extension methods can be used anywhere in the application by including the namespace that contains the extension methods.