« Assigning to C# events | Main | AllowDrop in WPF »

March 14, 2008

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 at March 14, 2008 11:07 AM

Trackback Pings

TrackBack URL for this entry:
http://blog.logos.com/mt-cgi/mt-tb.cgi/192

Comments

Post a comment




(you may use HTML tags for style)