Check for null in foreach loop

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 🙂

Leave a Comment