Create your own extension methods to use in LINQ






The possibility to create extension methods has been around for some time in the .Net Framework. It basically gives you the possibility to extend a class with new methods without having to create a new class that extends the original one. If the original class is sealed you can’t even extend the class, but you can still create extension methods and hook them onto that sealed class.

An extension method must have the following features to work:

  • Defined as public and static
  • Defined inside a static class
  • The first parameter must contain the this keyword and the type you’re extending

To illustrate we will create a simple extension method for the Int32 class. In this first example we’re using LINQ to select all odd numbers. Since there is no odd method built-in into the Int32 class we have to check each number inside the where clause.

int[] numberList = {1,2,3,4,5,6,7,8,9,10};
var oddNumbers = from num in numberList
                 where num % 2 != 0
                 select num;

To make the code a bit more easy to read we create an extension method to the Int32 class able to calculate this for us. The name of the class doesn’t really matter. You just include the namespace the class is created in and the extension method will automatically work in the class you want to extend.

public static class MyExtensions
{
  public static bool IsOdd(this int number)
  {
    return number % 2 != 0;
  }
}

With the extension method in place for the Int32 class we can update our LINQ query to use the new extension method. The result is a more readable code where the actual intention is more clear.

int[] numberList = {1,2,3,4,5,6,7,8,9,10};
var oddNumbers = from num in numberList
                 where num.IsOdd()
                 select num;






When using the extension method in Visual Studio the extension method is displayed differently in the method list. It even says (extension) in the method description. This is to say that it’s not really part of the Int32 class but rather an extension added outside of the original class.
Extension method

You can read more about extension methods on these places: