DEV Community

Cover image for Your favorite/most useful extension methods?
Russ Hammett
Russ Hammett

Posted on • Originally published at Medium on

Your favorite/most useful extension methods?

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 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:

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:

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:

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

Or as a NuGet Package:

Kritner.ExtensionMethods 1.0.1

Top comments (1)

Collapse
 
jastbytes profile image
Jan Steffen

Hey there,

pretty handy extension. I've a library with many extension methods myself on github.com/iss0/jastExtensions. I have some methods which somehow solve the same problem, but afterwards cleaning up the list or dictionary:

/// <summary>
/// Removes all elements from the collection which are null 
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    return source.Where(t => t != null);
}

/// <summary>
/// Removes every entry from the dictionary whose value is null
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dictionary"></param>
/// <returns></returns>
public static IDictionary<TKey, TValue> ValueNotNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
    if (dictionary == null)
    {
        throw new ArgumentNullException(nameof(dictionary));
    }

    return dictionary.Where(pair => pair.Value != null).ToDictionary(pair => pair.Key, pair => pair.Value);
}

These two methods are just a few I've found useful over time and are part of my library. Some limitations on extension methods will fall in future C# 8, see channel9.msdn.com/Blogs/Seth-Juare....