Check an object is not null before iterating over it

I'm getting an error System.ArgumentNullException: Value cannot be null. on the following:

 foreach (var pmt in payment.NewInvoiceViewModels
   .Where(x => x.PaymentReceived != 0) ?? 
    Enumerable.Empty<NewInvoiceViewModel>())

All I'm trying to do is check of payment.NewInvoiceViewModels is null before I iterate over it (if it is null, it causes an error).

Is there a better way of achieving this?

Jon Skeet
people
quotationmark

You've got the null-coalescing operator in the wrong place - currently you're calling Where on payment.NewInvoiceModels unconditionally and then checking whether the result will be null... it never will be (Where simply doesn't return null). You potentially want:

foreach (var pmt in (payment.NewInvoiceViewModels ?? 
                     Enumerable.Empty<NewInvoiceViewModel>())
                   .Where(x => x.PaymentReceived != 0))

Personally I'd extract this out though:

var allModels = payment.NewInvoiceViewModels ?? 
                     Enumerable.Empty<NewInvoiceViewModel>();

foreach (var pmt in allModels.Where(x => x.PaymentReceived != 0))

Or perhaps introduce an extension method:

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

Then:

foreach (var pmt in payment.NewInvoiceViewModels
                           .NullToEmpty()
                           .Where(x => x.PaymentReceived != 0))

people

See more on this question at Stackoverflow