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:
[Test] 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:
[Test] 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.