EmptyIfNull

Another great use for the fact that C# extension methods work on null references is a method we call EmptyIfNull:

    public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> seq)
    {
        return seq ?? Enumerable.Empty<T>();
    }

This extension method simply returns the specified enumerable, unless it is null, in which case it returns an empty enumerable. It requires slightly less typing than using the null-coalescing operator.

For example, suppose the GetNames method normally returns a collection of strings, but could return null if there are none. Either of these statements will write each of the strings to the console:

    (GetNames() ?? Enumerable.Empty<string>()).
        ToList().ForEach(Console.WriteLine);
    GetNames().EmptyIfNull().ToList().ForEach(Console.WriteLine);

I like the EmptyIfNull syntax better.

Posted by Ed Ball on March 14, 2008