What Are Extension Methods and How to Use Them

Introduction 

Extension methods are methods that can extend existing types without the need to inherit from a class and creating your own custom logic. It can also be applied to interfaces.


Figure 1 From MSDN

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling the derived type or otherwise modifying the original type. It means we can extend methods from any type, even types we don't have access to the source code for.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

We build extension methods by declaring it as a static method, but there is a little tweak that makes it compile into a method that can be called from an instance.

Extension methods were born in .NET 3.5 together with LINQ. LINQ was a major feature on the .NET Framework, it introduced several extension methods making data manipulation much easier. Some of the extension methods commonly used are Where, Select and Count.

So how do we create our own extension methods? Simple! We need a couple of things. First we need to create a static class.

I will provide an example extending strings. Additionally, for simplifying the process to truncate a string, I will create a method.
  1. namespace Example.Extensions   
  2. {   
  3.     public static class StringExtender   
  4.     {   
  5.     public static string TruncateAt(this string source   
  6.     ,   int maxLength)   
  7.     {   
  8.     if (source.Length <= maxLength)   
  9.     {   
  10.     return source;   
  11.     }   
  12.   
  13.     return source.Substring(0, maxLength);   
  14.     }   
  15.     }   
  16. }
This simple code will truncate a string. Did you notice something different? Yes, the parameter is declared as this string source. When we create a static class, a static method and use this before the first parameter, we meant to say that it is an extension method.

Now we will try to use it.
  1. "I will be truncated, lol!".TruncateAt(6);
Wait, are you getting a compilation error? If you are, the reason is simple. We created the extension method using the namespace, for example, Extensions. If we try to use it in another namespace we will need to add the using statement (in Visual Studio 2015 the light-bulb is smart enough to add it for you).

No errors? Did you notice that when we were calling our method we only passed one parameter instead of two? It is because the first one is the instance itself. The parameters passed to this method will be "I will be truncated, lol!" and 6.

Simple, isn't it? Do you want to see some complex examples? What about DistinctBy? It is a method that filters a list leaving only distinct elements comparing by a given expression.
  1. /// <summary>   
  2. /// Returns distinct elements from a sequence.   
  3. /// </summary>   
  4. /// <typeparam name="TSource">The type of the elements of source.</typeparam>   
  5. /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>   
  6. /// <param name="source">The sequence to remove duplicate elements from.</param>   
  7. /// <param name="keySelector">A function to extract the key for each element.</param>   
  8. /// <param name="comparer">An System.Collections.Generic.IEqualityComparer<T> to compare keys.</param>   
  9. /// <exception cref="System.ArgumentNullException">source or keySelector is null.</exception>   
  10. /// <returns></returns>   
  11. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,   
  12. Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null)   
  13. {   
  14.     if (source == nullthrow new ArgumentNullException("source");   
  15.     if (keySelector == nullthrow new ArgumentNullException("keySelector");   
  16.     var keys = new HashSet<TKey>(comparer);   
  17.     foreach (var element in source)   
  18.     {   
  19.     if (keys.Add(keySelector(element)))   
  20.     {   
  21.         yield return element;   
  22.     }   
  23.     }   
  24. }
If you are going to manipulate images, you could create a Crop method. And so on, the possibilities are limitless!

That's really cool, isn't it?

Hey, do you know about the morelinq project? The morelinq project is a collection of extension methods that allows you to do even more with LINQ. They have many pretty useful methods.

And when exactly is the best time to use extension methods and when should we be implementing/extending classes?

Well, at this point you got the general idea on when to use it.


Similar Articles