Linq operators on null Linq collection

You cannot apply the Linq operators (First, Single, Any, …) when the query returns null.

We have to add an extension method:

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

    return source;

And now you can write:

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


%d bloggers like this: