LINQ Extension Methods

LINQ Extension Methods in C# with Examples

In this article, I am going to discuss the LINQ Extension Methods in C# with examples. Please read our previous article before proceeding to this article where we discussed the Differences between IEnumerable and IQueryable in C#. At the end of this article, you will understand the following three concepts in C#.

  1. What are Extension Methods in C#?
  2. When to use Extension Methods in C#?
  3. How to implement extension methods in C#?
  4. Understanding the LINQ Extension Method.

The LINQ’s standard query operators such as select, where, etc. are implemented in Enumerable class. These methods are implemented as extension methods of the type IEnumerable<T> interface. Let us understand this with an example. We have the following code in our Main method.

LINQ Extension Methods in C#

The above Where() method is not belonging to List<T> class, but still, we are able to call it as it belongs to List<T> class. Why it is possible to call it using List<T> object, let’s find out. If you go to the definition of where method, then you will find the following definition.

Where Extension Method

As you can see in the signature, the where Where() method is implemented as an extension method on IEnumerable<T> interface and we know List<T> implements IEnumerable<T> interface. This is the reason why we are able to call the Where() method using the List<T> object.

With this keep in mind, let us understand what extension methods are and how they are implemented in C#.

What are Extension Methods?

According to MSDN, Extension methods allow us to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. 

In simple words, we can say that the Extension methods can be used as an approach of extending the functionality of a class by adding new methods in the future if the source code of the class is not available or if we don’t have any permission in making changes to the class.

The most important point that you need to keep in mind is, extension methods are the special kind of static methods of a static class, but they are going to be called as if they were instance methods on the extended type. 

When to use Extension Methods in C#?

You need to use an extension method if any of the following conditions are true:

  1. You need a method on an existing type and you are not the owner of the source code of that type.
  2. You need a method on an existing type, you do own the source code of that type but that type is an interface.
  3. You need a method on an existing type, you do own the source code and that type is not an interface but adding the method creates undesired coupling.

Otherwise, you should go with the normal method on the actual type itself.

How to implement extension methods in C#?

Let us understand this with an example. Our requirement is, we want to add a method in the built-in string class, let’s call this method as GetWordCount() which will count the word present in a string separated by a space.

For example, if the string is “Welcome to Dotnet Tutorials”, then it should return the word count as 4. The most important point is, we need to call this method on the String object as shown below.

int wordCount = sentence.GetWordCount();

Note: We cannot define the GetWordCount() method directly in the string class as we are not the owner of the string class. The string class belongs to System namespace which is own by the .NET framework. So, the alternative solution to achieve this is to write a wrapper class as shown below.

public class ExtensionHelper
{
    public static int GetWordCount(string str)
    {
        if (!String.IsNullOrEmpty(str))
            return str.Split(' ').Length;
        return 0;
    }
}

The above ExtensionHelper Wrapper class works fine, but the problem is, here we cannot call the GetWordCount() method using the string object as shown below.

int wordCount = sentence.GetWordCount();

Instead, we need to call the GetWordCount() method as shown below.

int wordCount = ExtensionHelper.GetWordCount(sentence);

How to convert the above GetWordCount() method to an Extension Method of string class?

Now let’s convert the GetWordCount() method to an extension method on the String class. So that we can able to call the GetWordCount() method using the following syntax.

int wordCount = sentence.GetWordCount();

In order to make the above GetWordCount() method as an extension method, we need to make two changes which are as follows.

  1. First, we need to make the ExtensionHelper class as a static class.
  2. Second, the type the method extends (i.e. string) should be passed as the first parameter preceding with the “this” keyword to the GetWordCount() method.

With the above two changes in place, now the GetWordCount() method becomes an extension method and hence we can call the GetWordCount() method in the same way as we call an instance method of a class.

The complete code is given below.
using System;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string sentence = "Welcome to Dotnet Tutorials";
            
            int wordCount = sentence.GetWordCount();

            Console.WriteLine($"Count : {wordCount}");
            Console.ReadKey();
        }
    }

    public static class ExtensionHelper
    {
        public static int GetWordCount(this string str)
        {
            if (!String.IsNullOrEmpty(str))
                return str.Split(' ').Length;
            return 0;
        }
    }
}

Now run the application and you will see the word count as expected in the console window. Here we are still able to call the GetWordCount() extension method using the wrapper class style syntax and also get the output as expected as shown below.

Wrapper Style Syntax

So, the point that I need to keep focus is, behind the scene this is how the extension methods are called internally.

How Extension Methods Execute Internally

That means, it is also possible to call the LINQ extension methods such as select, where, etc. using the wrapper class style syntax. As all the LINQ extension methods are implemented in the Enumerable class, So, the syntax to call those methods should looks as shown below.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            IEnumerable<int> EvenNumbers = Enumerable.Where(intList, n => n % 2 == 0);
            
            Console.ReadKey();
        }
    }
}

In the next article, I am going to discuss the LINQ Operators in C#. I hope this article will give you a very good understanding of the LINQ Extension Methods in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *