Never Return a Null Collection
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.
Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)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");
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





