Saturday, May 5, 2018

C#: What is extension method in c# and how to use them

Perhaps the best-known example of extension methods in .NET is LINQ. The vast majority of the API surface of LINQ is extension methods on the IEnumerable and IQueryable interfaces.
LINQ was added in .NET 3.0. If the LINQ team had decided to add the LINQ methods directly to IEnumerable, this would have constituted a breaking change. Every class which implemented IEnumerable would have been broken upon upgrading to .NET 3.0 until the _entire suite of LINQ methods was implemented._ Just imagine implementing that across every collection class. C# developers everywhere would have chased the LINQ team around with pitchforks.
Instead, the LINQ team implemented their system as extension methods. The result is that .NET 3.0 and LINQ were fully backward compatible with libraries written in .NET 2.0. Additionally, a whole lot of headaches and duplicated code were avoided. And it was done by, effectively, adding implementations to interfaces.

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

How to use extension methods?

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Like: suppose we have a class like bellow:
  1. public class Class1 {  
  2.     public string Display() {  
  3.         return ("I m in Display");  
  4.     }  
  5.   
  6.     public string Print() {  
  7.         return ("I m in Print");  
  8.     }  
  9. }  
Now we need to extend the definition of this class so m going to create a static class to create an extinction method like:
  1. public static class XX {  
  2.     public static void NewMethod(this Class1 ob) {  
  3.         Console.WriteLine("Hello I m extended method");  
  4.     }  
  5. }  
Here I just create a method that name is NewMethod with a parameter using this to define which type of data I need to be extend, now let’s see how to use this function.

ASP.NET

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         Class1 ob = new Class1();  
  4.         ob.Display();  
  5.         ob.Print();  
  6.         ob.NewMethod();  
  7.         Console.ReadKey();  
  8.     }  
  9. }  
Output will be: ASP.NET


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, IsGreaterThan() 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

int i = 10;

bool result = i.IsGreaterThan(100); //returns false 

The IsGreaterThan() 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.
Extension Method icon
Extension Method Symbol in visual studio intellisense
Now let's see how to write an extension method.
LINQ is built upon extension methods that operate on IEnumerable and IQeryable type.
An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class.
For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example. The IntExtensions class will contain all the extension methods applicable to int data type. (You may use any name for namespace and class.)
Example: Extension method

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 the this modifier.
For example, the IsGreaterThan() method operates on int, so the first parameter would be, this int i:
Define extension method in C#:

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.
Example: Extension method

using ExtensionMethods;

class Program
{

    static void Main(string[] args)
    {
        int i = 10;

        bool result = i.IsGreaterThan(100); 

        Console.WriteLine(result);
    }
}

Output:
false
Note :The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

Points to Remember :

  1. Extension methods are additional custom methods which were originally not included with the class.
  2. Extension methods can be added to custom, .NET Framework or third party classes, structs or interfaces.
  3. The first parameter of the extension method must be of the type for which the extension method is applibable, preceded by the this keyword.
  4. Extension methods can be used anywhere in the application by including the namespace of the extension method.

No comments:

Post a Comment