What is a extension method c#


C# - Extension Method

Extension methods, as the name suggests, are additional methods. Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface. Extension methods can be added to your own custom class, .NET framework classes, or third party classes or interfaces.
In the following example, IsgreaterThen() is an extension method for int type, which returns true if the value of the int variable is greater than the supplied integer parameter.
Example: Extension Method
  1. int i = 10;
    
    bool result = i.IsGreaterThan(100); //returns false 

The IsGreaterThen() method is not a method of int data type (Int32 struct). It is an extension method written by the programmer for the int data type. The IsGreaterThan() extension method will be available throughout the application by including the namespace in which it has been defined.
The extension methods have a special symbol in intellisense of the visual studio, so that you can easily differentiate between class methods and extension methods.
Example: Create a Class for Extension Methods

  1. namespace ExtensionMethods
    {
        public static class IntExtensions
        {
    
        }
    }


Now, define a static method as an extension method where the first parameter of the extension method specifies the type on which the extension method is applicable. We are going to use this extension method on int type. So the first parameter must be int preceded with this modifier.
For example, the IsGreaterThen() method operates on int, so the first parameter would be, this int i.
Example: Define an Extension Method

  1. 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 wherever you want to use this extension method.

  1. using ExtensionMethods;
    
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
    
            bool result = i.IsGreaterThan(100); 
    
            Console.WriteLine(result);
        }
    }


Post a Comment

0 Comments