0

I am trying to figure out the best way to handle this issue I have with ienumerable.sum null exception.

Basically I have a class that pulls the sum of its child objects as a return.

Something like this:

Part Class:

public ICollection<ContractLineItem> ContractLineItems { get; set; }
public float TotalReceiptSpendLong { get { 
       return ContractLineItems.Sum(s => s.TotalReceiptSpend);  
} }

The contractlineitems class contains a ICollection to a receipts class which is totaled in the contractLineItems TotalReceiptSpend float. This works fine unless a contractlineitem has no receipts. It then throws a null exception. Is there a way to handle this best?

eVeezy
  • 41
  • 2
  • The collection wasn't initialized. The result should be 0 if the set was empty (but initialized). – Jasen Dec 28 '17 at 00:33
  • Possible duplicate of [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) – juunas Dec 28 '17 at 08:30

1 Answers1

0

Consider using Null-conditional Operators (C# and Visual Basic) along with ?? Operator (C# Reference)

 return ContractLineItems?.Sum(s => s?.TotalReceiptSpend ?? 0) ?? 0;

That way if any of the above referenced variables are null it will default to zero (0) and avoid the null reference error when calling Sum

Nkosi
  • 235,767
  • 35
  • 427
  • 472