Los Techies : Blogs about software and anything tech!

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.

Kick It on DotNetKicks.com
Posted Dec 08 2009, 06:42 PM by bogardj
Filed under:

Comments

John Farrell wrote re: LINQ query operators and null lists
on 12-09-2009 12:00 AM

Nice, this the most useful 4 lines of code I've seen in a while.

Vitaly Stakhov wrote re: LINQ query operators and null lists
on 12-09-2009 1:41 AM

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.

Reflective Perspective - Chris Alcock » The Morning Brew #494 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #494
on 12-09-2009 3:24 AM

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #494

Sanjeev Agarwal wrote Daily tech links for .net and related technologies - December 9-10, 2009
on 12-09-2009 6:01 AM

Daily tech links for .net and related technologies - December 9-10, 2009 Web Development Organizing ASP

Tommy Carlier wrote re: LINQ query operators and null lists
on 12-09-2009 8:42 AM

You could make that shorter by using the coalescing operator:

public static IEnumerable<TSource> NullToEmpty<TSource>(

 this IEnumerable<TSource> source)

{

   return source ?? Enumerable.Empty<TSource>();

}

Mike wrote re: LINQ query operators and null lists
on 12-09-2009 8:44 AM

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

return source ?? Enumerable.Empty<TSource>();

bogardj wrote re: LINQ query operators and null lists
on 12-09-2009 9:19 AM

@Tommy, @Mike

Nice!  Thanks for the tip!

Twitter Trackbacks for LINQ query operators and null lists - Jimmy Bogard - Los Techies : Blogs about software and anything tech! [lostechies.com] on Topsy.com wrote Twitter Trackbacks for LINQ query operators and null lists - Jimmy Bogard - Los Techies : Blogs about software and anything tech! [lostechies.com] on Topsy.com
on 12-09-2009 9:23 AM

Pingback from  Twitter Trackbacks for                 LINQ query operators and null lists - Jimmy Bogard - Los Techies : Blogs about software and anything tech!         [lostechies.com]        on Topsy.com

superbecio wrote re: LINQ query operators and null lists
on 12-09-2009 10:10 AM

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.

Wes McClure wrote re: LINQ query operators and null lists
on 12-10-2009 1:09 AM

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!

Friday Links #80 | Blue Onion Software * wrote Friday Links #80 | Blue Onion Software *
on 12-11-2009 7:03 PM

Pingback from  Friday Links #80 | Blue Onion Software *

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

Enter the numbers above:
Copyright Los Techies 2008, 2009. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems