Extension Method in C#

extension methods in c sharp

Have you been in a situation where you wished to have some method in some class that you can’t modify (for example .Net classs)? I never thought in that direction until I came across this wonderful feature in C#, The Extension Method.

So what is Extension Method?

Extension Method enables you to add methods in existing classes without modifying them or creating a subclass. So we can think of them as a candidate that could help up follow Open Closed Principle of SOLID Principles because here too, we are adding behaviours without directly modifying the class. Technically, extension methods are not part of a class, they are just static methods but you can call them as they are part of it. Lambda expressions extensively use them. Some of the examples are Select, OrderBy etc. Since I came to know about them I always tried to find a way to sneak them in, they are just awesome.

The Scenario:

We had a scenario where we used to retrieve list of objects by passing list of IDs to WCF service. We were passing tens of thousands of IDs and that was causing service to go into irresponsive state. Other methods were timing out while waiting for this method to complete. We decided retrieve objects in chunks to reduce the load. I could have achieved it by just dividing list into chunks and use them one by one but why doing that when I have better and cooler way of doing that? ­čśë Here is sample code for achieving this by using Extension Methods.

class Program
{
    static void Main(string[] args)
    {
        //set up
        var IDs = new List<int>();
        for (int i = 1; i <= 52; i++)
        {
            IDs.Add(i);
        }
        //Extension method in action
        foreach (var chunk in IDs.Chunks(10))
        {
            Console.WriteLine($"Fetching data for next " +
                    $"{chunk.Count} IDs...");
            foreach (var i in chunk)
            {
                Console.WriteLine($"Fetching data for ID: {i}");
            }
        }
        Console.ReadLine();
    }
}
static class Extensions
{
    public static List<List<int>> Chunks(this List<int> input
    , int chunkSize)
    {
        var chunks = new List<List<int>>();
        for (int i = 0; i < input.Count; i+=chunkSize)
        {
            chunks.Add(input.Skip(i).Take(chunkSize).ToList());
        }
        return chunks;
    }
}
Output:
Fetching data for next 10 IDs...
Fetching data for ID: 1
Fetching data for ID: 2
Fetching data for ID: 3
Fetching data for ID: 4
Fetching data for ID: 5
Fetching data for ID: 6
Fetching data for ID: 7
Fetching data for ID: 8
Fetching data for ID: 9
Fetching data for ID: 10
Fetching data for next 10 IDs...
Fetching data for ID: 11
Fetching data for ID: 12
Fetching data for ID: 13
Fetching data for ID: 14
Fetching data for ID: 15
Fetching data for ID: 16
Fetching data for ID: 17
Fetching data for ID: 18
Fetching data for ID: 19
Fetching data for ID: 20
Fetching data for next 10 IDs...
Fetching data for ID: 21
Fetching data for ID: 22
Fetching data for ID: 23
Fetching data for ID: 24
Fetching data for ID: 25
Fetching data for ID: 26
Fetching data for ID: 27
Fetching data for ID: 28
Fetching data for ID: 29
Fetching data for ID: 30
Fetching data for next 10 IDs...
Fetching data for ID: 31
Fetching data for ID: 32
Fetching data for ID: 33
Fetching data for ID: 34
Fetching data for ID: 35
Fetching data for ID: 36
Fetching data for ID: 37
Fetching data for ID: 38
Fetching data for ID: 39
Fetching data for ID: 40
Fetching data for next 10 IDs...
Fetching data for ID: 41
Fetching data for ID: 42
Fetching data for ID: 43
Fetching data for ID: 44
Fetching data for ID: 45
Fetching data for ID: 46
Fetching data for ID: 47
Fetching data for ID: 48
Fetching data for ID: 49
Fetching data for ID: 50
Fetching data for next 2 IDs...
Fetching data for ID: 51
Fetching data for ID: 52

Explanation: We know that there is no Chunks method in class List<T> for dividing list into smaller chunks for lists but here I created an Extension Method that just does that. I have also called that method on IDs as if it was a part of class List<T>. There is a list of 52 IDs but I want to fetch data for maximum 10 IDs at a time. So I created a method that divides this list into 6 smaller lists, 5 lists will contain 10 IDs and one contains 2 items. I have also used 2 inbuilt methods, Skip and Take, which is what? Extension Methods ­čÖé

Why to use extension method while you can add behaviour to a class using inheritance?

You can do it by using inheritance but inheritance comes with it’s own cons. It creates tight dependencies between classes.

One more reason for not using inheritance is, it will add it’s public and protected methods to your class and you don’t want it all the time.

Please leave the feedback for questions/suggestion. Happy coding.

Leave a Reply

Your email address will not be published.

Coding Crest Back To The Top