Dealing with iterations over null lists in LINQ to Objects

Problem

If you used LINQ to Objects you have certainly come across iterations over null values resulting in an ArgumentNullException being thrown at you.

See this example:

int[] b = null;
var query = from i in b select i;

In the case above the error is obvious but if the list comes as an argument of a method or some more complicated way it is hard to spot it. Sure, the obvious solution is an easy one. A simple if statement before will do it:

if (b != null)
    var query = from i in b select i;

What about nested loops? Like this

class Tubo
{
    public List<string> Strings;
}
...
IList tubos = ...;
var query = from t in tubos
            from s in t.Strings
            select s;

Sure, we could add guardian clauses like the if before:

if (tubos != null)
     var query = from t in tubos
        where t.Strings != null
        from s in t.Strings
        select s;

The problem with this approach is that it gets cluttered and it complicates the flow, specially the first if.

Solution

So, here is my proposal and I am sure it has been proposed before (I just couldn’t find it on Google, err, I mean internet).

public static class Extension
{
    public static IList Safe(this IList source)
    {
        if (source == null)
            return new T[0];
        else
            return source;
    }
}

The extension method makes sure that query always gets a non-null list by making an empty one if it is null. The trick with extension method is that they can be invoked on null values which are passed as this argument.

And the last nested LINQ to Objects loop would look like:

var query = from t in tubos.Safe()
             from s in t.Strings.Safe()
             select s;

I am not sure that the extension method name Safe is adequate or not but it sure does help in code readability.

What do you say?


Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.