Member-only story
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…