Extension method - basic understanding
Extension method - basic understanding

Extension method helps us by reducing the amount of object initiatilization and thereby lessen our code. It is so useful that the Microsoft guys wrote one of their most popular libraries of nowadays called “LINQ” using this extension method technique.

As extension method resides in a static class we don’t (can’t) need to bother about deriving and recompiling our code when we have written an extension method. Its a huge help when we want to have some customized behaviour to an existing type. Because, all the built-in (system) types are in nature not modifiable. In that case, extension method is the life saver. Allow me to explain with examples


Scenario:

Suppose, you want to get all the even numbers from a list of numbers (I know it is so trivial. but it will cover the concept for now). Well, you can just write your own method in your code-base and there will be no problem. But let’s say we want to keep all our processing code in a separate class, call it “NumberProcessor”. Now in our “NumberProcessor” class we can have the following method:

public IEnumerable<int> GetAllEvenNumbers(IEnumerable<int> numbers)
        {
            foreach (var number in numbers)
            {
                if (number / 2 == 0)
                {
                    yield return number;
                }
            }
        }

And then we can use this method under our “NumberProcessor” class like below:

//initialize NumberProcessor
var numProcessor = new NumberProcessor();  
var numbers = new[] { 1, 2, 4, 5, 6, 8, 12, 11, 13, 15, 21, 22, 30 };
//call desired method from NumberProcessor instance
var evenNumbers = numProcessor.GetAllEvenNumbers();
foreach(number in numbers){
    Console.WriteLine(number);
}

Notice, we have to create a complete new instance of NumberProcessor class to call the method we need. We also need to use the numProcessor variable to call the method. 

How to write an extension method

Well, we can declare the class and method both as static and then we don’t need to create an instance of the “NumberProcessor” class at all. We can then directly call the method we need. 

//class declaration
public static class NumberProcessor {
public static IEnumerable<int> GetAllEvenNumbers(IEnumerable<int> numbers)
        {
            foreach (var number in numbers)
            {
                if (number / 2 == 0)
                {
                    yield return number;
                }
            }
        }
}
//method call
var numbers = new[] { 1, 2, 4, 5, 6, 8, 12, 11, 13, 15, 21, 22, 30 };
//call desired method directly
var evenNumbers = NumberProcessor.GetAllEvenNumbers();
foreach(number in numbers){
    Console.WriteLine(number);
}

This generate another new hiccup. Meaning any time we need the “GetAllEvenNumbers” method, we have to mention the class name before it.
We can get rid of this problem by using the “this” keyword like below

//class declaration
public static class NumberProcessor {
public static IEnumerable<int> GetAllEvenNumbers(this IEnumerable<int> numbers)
{
   foreach (var number in numbers)
            {
                if (number / 2 == 0)
                {
                    yield return number;
                }
            }
        }
}
//method call
var numbers = new[] { 1, 2, 4, 5, 6, 8, 12, 11, 13, 15, 21, 22, 30 };
//notice no class name
var evenNumbers = numbers.GetAllEvenNumbers();
foreach(number in evenNumbers ){
    Console.WriteLine(number);
}

Now it looks like that the IEnumerable type has a method called “GetAllEvenNumbers”. This allows us to call this method where ever we are dealing with IEnumerable type. Because, by using the “this” keyword in our “GetAllEvenNumbers” method we added this feature to IEnumerable types or extended its functionality.

Issues to care about

Calling or using extension method is no different than using or calling any normal method. However, there are a few things to be careful about while creating an extension method. Such as, we have to make sure that the method we are creating is a static one and it resides in a static class and we are using the “this” keyword in front of the first parameter type in the method.

Sometimes, our static class may reside under different namespace. In that case referencing to that namespace by using the “using” keyword is a must if we want to call our extension method. 

March 20, 2015
Jahan Sarwar