Friday, December 18, 2009

The design flaw of foreach

The foreach loop contruct in C# is very useful, but it has one major design flaw. The design flaw I'm thinking of is the NullPointerException it throws when it's given a collection that is null.
I do realize that it makes sense to throw an exception when no input is provided. The problem is that I have never seen an application that expects an exception from the foreach contruct.
With foreach you must know that the collection is set, or wrap the whole thing in a check for null. This adds an extra codeblock to your code.

I have created an extension method for collections so I can avoid the extra codeblock and do something like this:

IList<SomeObject> list = GetObjects();
foreach(SomeObject o in list.NullChecked()){

Even if the GetObjects() method returns null your code wont fail. It just doesn't execute the loop.

public static IEnumerable<T> NullChecked<T>(this IEnumerable<T> input){
        return input;
        return new List<T>();


  1. Any time you reference an object in .net that is null you will get an exception. I don't think it is a design flaw at all. The code can't iterate through a list that does not exist.

  2. Arguably, the real problem is GetObjects() returning null, when an empty Collection would be the usual way of saying "I have no content, but all is good and well". Returning null rather indicates an invalid operation or exceptional circumstances.

    Thus don't think trying to iterate over null should silently fail, but give indication of an error, as the intention of "there just isn't anything there" is already better expressed by the empty list.

  3. My intend was to use this on domain models. With domain models I would say the focus is on whether a collection contains elements or not... whether the collection is null or just empty often means the same thing.