-1

The following line of code:

double? paidAmount = invoices.Value.Where(x => x.Status.Equals(Constants.InvoicePaid)).Sum(x => x.TotalAmount);

Is causing an error when the status is null.:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Can I avoid this exception using null-coalescing? If interested, here I'm checking if the status property is equal to "paid" I want to sum.

Trevor
  • 7,777
  • 6
  • 31
  • 50
someone
  • 139
  • 1
  • 12
  • We need more information. Which property exactly is throwing the exception ? – Fabjan May 28 '21 at 19:49
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) On another note, `Can I avoid this exception using null-coalescing?` have you tried it, what was the results? – Trevor May 28 '21 at 19:53
  • Another option, do you have a choice of `Constants.InvoiceNotPaid` or maybe `Constants.InvoiceNew`, it would be helpful as it could be the default for `Status`... unless `null` is a valid value for notpaid/unknown etc... – Trevor May 28 '21 at 20:05
  • @Fabjan the Status property is causing the exception – someone May 28 '21 at 21:32

1 Answers1

0

You can use the null coalescing operator:

double? paidAmount = invoices.Value.Where(x => x.Status?.Equals(Constants.InvoicePaid)).Sum(x => x.TotalAmount);

This will evaluate to false if the Status is null.

ekke
  • 1,280
  • 7
  • 13
  • 1
    `x` shouldn't ever be null, so I don't think you need that conditional operator there. – Tieson T. May 28 '21 at 19:55
  • Noted, I've updated. – ekke May 28 '21 at 19:58
  • @ekke it doesn't work it cause compiler error: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type – someone May 28 '21 at 21:42