Cool .NET extension methods

March 23rd, 2016 Duco Winterwerp c-sharp .net asp.net microsoft windows programming tutorial

Download the code from GitHub!

In this article, I’ll let you show some cool extension methods which you can use right away in your .NET project; they don’t need any external libraries (apart from .NET) to be executed.

Extension methods?

I'll explain what extension methods are if you didn’t know this already. They are one of the things I really love about the .NET framework. An extension method is essentialy a static method in a static class that accepts parameters just like any other method. The big difference is the "this" modifier for the first parameter in the method. Let’s take a look:

public static string Blah(this string input)
{
    return input.Replace("blah", "foo");
}

You can execute the method like this:

string text = "blahblah";
text = text.Blah();
Console.WriteLine(text); //foofoo

As you can see, you can now directly invoke the Blah() method on the string, like it’s an instance method (but it isn’t). Visual Studio knows about your extension and gives you intellisense when you want to invoke a method on your variable.

Besides this, extension methods are just static methods and some people may call it a code smell. This article is, however, about extension methods which make your development life a little bit easier.

'Set' function

This is an extension method on the object class in .NET, which means every instance of every object has this extension method available. This extension method accepts an instance of a class and passes it to a callback method, where you can change the instance. The instance is then returned.

The method itself

public static T Set<T>(this T obj, Action<T> action)
{
  action(obj);
  return obj;
}

An example

Person person = new Person().Set(p =>
{
  p.FirstName = "John";
  p.LastName = "Doe";
  p.Address = "Groningen, Netherlands";
  p.DateOfBirth = new DateTime(1993, 8, 29);
});

This is the more traditional way to write such an expression:

Person person = new Person()
{
  FirstName = "John",
  LastName = "Doe",
  Address = "Groningen, Netherlands",
  DateOfBirth = new DateTime(1993, 8, 29)
};

I use the Set method a lot in unit tests, because it allows me to quickly set up a big mock data set. It also allows me to directly execute method calls when assigning variables.

WhereIf

This is a LINQ extension method. In essence, this is a method which accepts a boolean and an expression. If the boolean is true, the expresion is executed. If the boolean is false, the expression is not executed, so the WhereIf statement is basically ignored.

The method itself

public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool shouldExecute, Func<TSource, bool> predicate)
{
  if (shouldExecute)
  {
    return source.Where(predicate);
  }
  return source;
}

An example

var items = new List<string>() { "aa", "ab", "ba", "bb" };
var subItems = items.WhereIf(false, i => i.StartsWith("a")).ToList();

Because the boolean is false, the expression is not executed so the original list will be returned.

Random

This is a method which returns a random element from any IEnumerable.

The method itself

public static T Random<T>(this IEnumerable<T> enumerable)
{
  return enumerable.OrderBy(e => Guid.NewGuid()).FirstOrDefault();
}

An example

var items = new List<string>() { "aa", "ab", "ba", "bb" };
var randomItem = items.Random();

It is not "really" random, as GUID is used for picking the item, but it's random enough for practical use.

Random selection

This extension method accepts any enumerable and returns a random selection of count items.

The method itself

public static IEnumerable<T> RandomSelection<T>(this IEnumerable<T> enumerable, int count)
{
  count = enumerable.Count() < count ? enumerable.Count() : count;
  return enumerable.OrderBy(e => Guid.NewGuid()).Take(count);
}

An example

var numbers = Enumerable.Range(0, 100);
var randomSelection = numbers.RandomSelection(10).ToList();

An array with numbers from 0 to 100 is defined. The second line gives us a random selection of those numbers.

Enumerable IsNullOrEmpty

This is a simple extension that takes any enumerable and checks if it is null or if the length is 0.

The method itself

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable == null || enumerable.Count() == 0;
}

An example

string[] stringArray = new string[0];
bool empty = stringArray.IsNullOrEmpty(); //true

Parse enum by string

This is a simple extension method which accepts an Enum type and a string. The method then tries to parse this string to an Enum value.

The method itself

public static T ParseEnum<T>(this string input) where T : struct, IConvertible
{
  if (!typeof(T).IsEnum)
  {
    throw new ArgumentException("{0} is not an Enum", typeof(T).Name);
  }
  T result = default(T);
  Enum.TryParse(input, out result);
  return result;
}

An example

string value = "Monday";
DayOfWeek dayOfWeek = value.ParseEnum<DayOfWeek>();

AppendFormatLine for StringBuilder

I love the StringBuilder. It is one of the most efficient ways to generate a string in the .NET framework. I didn't like the fact that I there was no direct method available to do a string format and a new line. This extension method does just that.

The method itself

public static StringBuilder AppendFormatLine(this StringBuilder stringBuilder, string format, params object[] args)
{
    return stringBuilder.AppendLine(string.Format(format, args));
}

An example

StringBuilder builder = new StringBuilder();
builder.AppendFormatLine("This is line {0}.", 1);
builder.AppendFormatLine("This is line {0}.", 2);