LINQ query operators and null lists

One of my pet peeves with the LINQ extension methods is their inability to handle null source lists.  For example, this will throw an ArgumentNullException:

public void Should_handle_nulls()
    List<int> ints = null;

    ints.Any(num => num < 0).ShouldBeFalse();

Now I know what you’re saying – why not check for null, or not allow the list to be null in the first place?  After all, the Framework Design Guidelines book recommends that methods and properties that return collection types never be null.  This is so you can merely check for empty collections, and not force users to have null checks everywhere.  That’s all fine and dandy…until you’re forced to interact with systems that don’t play nice.  Especially around serialization libraries, we find places where they don’t abide by this suggestion.

Instead, we have to add a rather annoying, but necessary extension method:

public static IEnumerable<TSource> NullToEmpty<TSource>(
    this IEnumerable<TSource> source)
    if (source == null)
        return Enumerable.Empty<TSource>();

    return source;

And now my test will pass, as long as I make sure and convert these values properly:

public void Should_handle_nulls()
    List<int> ints = null;

    ints.NullToEmpty().Any(num => num < 0).ShouldBeFalse();

So yes, it’s annoying, and I’d rather the LINQ operators just ignore null collections, or replace them with Enumerable.Empty().  Until then, we just have to use this annoying extension method.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in LINQ. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Nice, this the most useful 4 lines of code I’ve seen in a while.

  • Vitaly Stakhov

    Conceptually you’re trying to see if there is an element in ‘null’ collection. Sometimes it’s like division by zero.

    If Microsoft ignored null collections, that would be similar to mark all classes in the project as [Serializable] (yes, there are benefits – you don’t get SerializationException, but objects that are not expected to be serialized actually will be).

    So, my point is to leave constraints as tough as possible. Anyway, there is always a choice either to define/use NullOrEmpty or not. If nulls were ignored by extension methods the choice would not exist.

    There could be an option in linq inself to ignore or not though.

  • You could make that shorter by using the coalescing operator:

    public static IEnumerable NullToEmpty(
    this IEnumerable
    return source ?? Enumerable.Empty

  • Save yourself a few lines of code by using a null-coalescing operator

    return source ?? Enumerable.Empty();

  • @Tommy, @Mike

    Nice! Thanks for the tip!

  • superbecio

    I don’t agree with the fact that methods returning collections should never return null, rather I prefer to use that special value as a signal for user canceled operations.

  • Yeah, my biggest pet peeve is ForEach exploding with null sources… why not just ignore it? I try to always silently ignore null sources in extension methods unless it really doesn’t make sense.

    Wouldn’t it be nice if regular instance methods worked like python by taking the instance as a parameter so we could silently deal with nulls there too!

  • Mohsen Afshin

    Thank you