Your favorite/most useful extension methods?
Tags: discuss, csharp, dotnetcore, softwareengineering
Published: 2018-11-08 18:05:53

---
title: Your favorite/most useful extension methods?
published: true
tags: discuss,csharp,dotnet-core,software-engineering
canonical_url: https://medium.com/@kritner/your-favorite-most-useful-extension-methods-a63f4dc1cff2
cover_image: https://cdn-images-1.medium.com/max/1024/0*t-SCxoR9F2JzmwtW
---

Extension methods are pretty great! They’re a means of adding functionality to code without needing to actually touch the original source!

The [Microsoft docs](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) define an extension method as:

> Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The above sounds pretty nice, but doesn’t seem to even touch on the fact that you can apply extension methods to code where you don’t even have the source!

Extension methods can be quite useful, but as the documentation says, use them sparingly. If the implementation of the underlying object you’re creating an extension method for changes, that could lead to some issues.

An example of a situation where I like to use extension methods:

```cs
public void DoStuff()
{
 List<IUser> users = new List<IUser>();
 
 var employee = GetEmployee(_somePredicate);
 if (employee != null)
 {
  users.Add(employee);
 }
 
 var manager = GetManager(_someOtherPredicate);
 if (manager != null)
 {
  users.Add(manager);
 }
}
```

In the above, we have a fair amount of nesting of code, just due to checking for nulls prior to doing in an insert onto a list. Extension methods can help to make this code much cleaner looking!

The extension method `AddIfNotNull`:

```cs
public static void AddIfNotNull<T>(this IList<T> obj, T item)
{
 if (obj == null)
 {
  throw new ArgumentNullException($"{nameof(obj)} is null");
 }

 if (item == null)
 {
  return;
 }

 obj.Add(item);
}
```

The above adds a new function to `IList<T>` and anything implementing it. Within the function, we check if the item to be added to the `IList<T>` is `null`; if it is we do nothing, if it isn’t we add it. Great, so how does this help us?

Well, let’s take a look at what the earlier snippet can look like, with the extension method:

```cs
public void DoStuff()
{
 List<IUser> users = new List<IUser>();

 users.AddIfNotNull(GetEmployee(_somePredicate));
 users.AddIfNotNull(GetManager(_someOtherPredicate));
}
```

That code is a lot shorter, and (I think) easier to read!

I added a few more to a repository (link near bottom). The current extension methods include:

- `IList.AddIfNotNull` — already described
- `IList.AddRangeIfNotNull` — similar to above, just on a multiple object level
- `IEnumerable<T>.TryFirst` — attempt to get an item from a list, with bool as return and actual object in out param — similar to how `int.TryParse` works.

What are some of your favorite useful extension methods? Feel free to respond below, or submit a PR!

Code (as of writing) can be found:

[Kritner-Blogs/ExtensionMethods](https://github.com/Kritner-Blogs/ExtensionMethods/releases/tag/v1.0.1)

Or as a NuGet Package:

[Kritner.ExtensionMethods 1.0.1](https://www.nuget.org/packages/Kritner.ExtensionMethods/)