ForEach - Source Null Checking

Programming C#

The looooooooong way of doing things:

var someCollection = GetSomeCollectionFromSomewhere();

if (someCollection != null && someCollection.Count > 0)
{
foreach(var item in someCollection)
{
// Do stuff
}
}

Adding a one line extension method can massively simplify the above code pattern across an entire application:

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

Now we can simply do

var someCollection = GetSomeCollectionFromSomewhere();

foreach(var item in someCollection.OrEmptyIfNull())
{
// Do stuff
}

OK that looks better. But we can shorten this even further:

someCollection.OrEmptyIfNull().ToList().ForEach(x => x.DoSomething());