Check for null in foreach loop

Eminem picture Eminem · Jul 31, 2012 · Viewed 75k times · Source

Is there a nicer way of doing the following:
I need a check for null to happen on file.Headers before proceeding with the loop

if (file.Headers != null)
{
  foreach (var h in file.Headers)
  {
   //set lots of properties & some other stuff
  }
}

In short it looks a bit ugly to write the foreach inside the if due to the level of indentation happening in my code.

Is something that would evaluate to

foreach(var h in (file.Headers != null))
{
  //do stuff
}

possible?

Answer

Jon Skeet picture Jon Skeet · Jul 31, 2012

Just as a slight cosmetic addition to Rune's suggestion, you could create your own extension method:

public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

Then you can write:

foreach (var header in file.Headers.OrEmptyIfNull())
{
}

Change the name according to taste :)