Never return null collection

Empty or null, that is the question The distinction between an empty collection and a non-existent collection is rarely required. If a method is supposed to return IEnumerable<T>, you should definitely return Enumerable.Create<T>(). It is simply horrifying that one should return null to indicate that the collection does not have any elements or that some error happened.

Chaining LINQ operators should never be followed with the question “but what if the collection is null?” It should never be null, only empty.

If you have some method for which you are unsure if it will return null or if you know that it can return null, but you do not want to handle that, you can use this handy extension method:

public static IEnumerable<T> Ensure<T>(this IEnumerable<T> @this)
{
    return @this ?? Enumerable.Empty<T>();
}

Now you can be sure that the LINQ query is well formed by simply chaining the Ensure method after a problematic function call:

conglomerate.GetValidCompanies()
            .Ensure() // don't worry
            .Where(c => c.Country == "Germany");

Last updated by at .

  • Sander Säde

    Uh, this is really bad advice..

    Instead of using myCollection == null – probably the cheapest check that exists in .NET framework – you create the collection and then have to check myCollection.Count == 0. KISS.

    And if you’re using EF or really, any other queries, like in your last example, then you’re doing it wrong – you send the predicate to the data layer method that returns your list in the first place.

    In effect, you’re using a database in conglomerate.GetValidCompanies(), you are doing:

    SELECT * FROM companies WHERE valid = 1

    possibly returning lots of non-needed matches whereas if your SQL query would be:

    SELECT * FROM companies WHERE valid = 1 AND country = ‘Germany’

    you would get only required entities back.

    • http://www.tonicodes.net/blog/ Toni Petrina

      I think you misunderstood me, GetValidCompanies() is an ordinary class method which returns List or ArrayList. This is an example from a legacy project and you can find such methods (especially if the project started in .NET 1.1 or 2.0 era).

      And in some cases implementation returns null which is not practical. Instead of modifying such functions directly (something you might not be able to do since you cannot modify the source), you need to ensure that the method returns valid collection if you want to use it seamlessly in your LINQ queries.
      Hence the Ensure method – force null value into correct empty IEnumerable instance.
      Also, myCollection.Count == 0 is inferior to myCollection.Any() since first method is not always available (think IEnumerable) and if you call the Count() extension, you might end up traversing a potentially large collection.

      • Sander Säde

        Ah, I didn’t realize it was an one-off solution, my bad.

        I do like the idea of Ensure(), although I doubt I will have a chance to use it much.

        As for the Count() – exactly, that is one of the reasons to return null and check for null instead of returning an empty collection.

  • http://www.vincebullinger.com Vince Bullinger

    Why don’t you just say “return @this ?? Enumerable.Empty();”

    • http://www.tonicodes.net/blog/ Toni Petrina

      Well, it is shorter :) Thanks, I will fix it.

      • http://www.vincebullinger.com Vince Bullinger

        Good Guy Toni. Takes constructive criticism. Fixes blog post. You are a rarity on the interwebz, my friend. My hat goes off to you.

        • http://www.tonicodes.net/blog/ Toni Petrina

          And you sir, are too kind :)