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:
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
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
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:
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
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:
Or as a NuGet Package: