.NET Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 49 posts at DZone. You can read more from them at their website. View Full User Profile

Never Return a Null Collection

09.14.2012
| 1531 views |
  • submit to reddit
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)
{
    if (@this == null)
        return Enumerable.Empty<T>();

    return @this;
}

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");
Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)