Defensive programming to prevent System.ArgumentNullException: Value cannot be null

This post is about how to prevent the System.ArgumentNullException: ‘Value cannot be null’ that usually originates from LINQ expressions where the IEnumerable source is null. I have come across this exception so many times in production environments so I decided to write this short post which hopefully raises awareness how this can be prevented by applying a defensive programming practise.

We are using the good old customer/order entities for this example:

And an example where we would see the infamous exception:

If we want to prevent this exception we can create the following simple but very effective generic extension method:

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

Now we change the above code to use the new extension method and the code will run without any exception:

In a lot of use cases we have IEnumerables that are only occasionally populated and they can cause a lot of headache in production environments. But the extension method described above will allow you to ensure your code is not failing under those circumstances.