Never Return a Null Collection
Join the DZone community and get the full member experience.
Join For Freethe 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");
Database
Operator (extension)
Element
Opinions expressed by DZone contributors are their own.
Comments