Creating LINQ Extension

Creating extensions  is one of the very useful techniques in C# that can help us extend the functionality of an existing class or library without modifying the origin. It is also aligned with the 2nd principle of SOLID programming, Open Close Principle.

In this article I will focus on creating a LINQ extension method and will point out a simple but important tip that you need to watch out for.

As we know LINQ query has lazy and greedy operators. In short the lazy operators act when is needed and greedy operators will capture the whole data even if it is not needed.  As an example, ToArray is a greedy and Where is a lazy operator.

When extending LINQ, it is very important to write the extension method in a way that works under both situations.

In this example I’m going to implement a new LINQ extension method called Log which is responsible for logging the items in the query.

The code below shows the usage of the extension method in a lazy way:

Check the following **wrong** implementation:

That gives us the following output:

As normal as it may look, it’s wrong and probably not what you wanted to do. As you can see all the calls to Log extension have happened before iterating the query. That is basically doing what we want but in a greedy way. As our LINQ query doesn’t have any sign of greedy operators being used in it (e.g. ToArray) then we can conclude that our extension method always run in a greedy way. Add ToArray to the end of the query and see if anything changes.

Now check the correct implementation:

Which will give us the following output:

As you can see in the recent output Log is happening as we iterate through the query in a correct lazy way.

This time if you add ToArray to the end of the LINQ query you will see that the same extension with no change runs in a greedy way.


Leave a Reply

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