Over a million developers have joined DZone.

Never Return a Null Collection

DZone's Guide to

Never Return a Null Collection

· ·
Free Resource
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:

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}