I wish that C#…doesn’t throw when iterating over null collection

Consider the following code:

List<string> list = null;
foreach (var element in list)
  //... NullReferenceException above

Boom, in your face! We want to go through all elements in the nonexisting collection. Not empty, but nonexisting. While you may argue that semantically there is some difference, when do you actually want that exception to blow up? Fix is easy, but ugly:

if (list != null)
{
    foreach (var element in list)
        //
}

One way to implement this would be to allow a compiler flag that will expand foreach (var element in list) into:

if (list != null)
    foreach (var element in list)

This is the same question as before: should you ever return null collections.

My answer is no, forget the null and make code prettier :)

Last updated by at .

  • TcKs

    Hi, I made a extension method “IEnumerable IgnoreNulls(this IEnumerable self)” which do the null-check first and then call “yield break” or “yield return” for not-null items in passed collection. It saved me a lot of time. I hope, it will safe you too.