0

I have the following piece of code.

(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)

I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

Wheels73
  • 2,850
  • 1
  • 11
  • 20

2 Answers2

0

You need to check everything that could be null. I just assume billInfo could be null too. Also The order of the statements is important here.

(billInfo != null && !string.IsNullOrEmpty(billInfo.BillingMethod) || (bill != null && !billInfo.BillingMethod?.Equals(bill))
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
  • Sorry I should have added the full line if (!string.IsNullOrEmpty(billInfo.BillingMethod) || (billCheck.BillingMethod != null && (!(billInfo.BillingMethod.Equals(billCheck.BillingMethod))))) – CaptainMonty Jun 07 '17 at 16:26
0

NullReferenceException can occur if billInfo or BillingMethod is null. So first checking for billInfo not equal to null, then check for other conditions. Also, the condition after the || is the other way around. As there is no point of checking not null if the first statement is failed.

Try this instead:

 if(billInfo != null && (!string.IsNullOrEmpty(billInfo.BillingMethod) ||
                        (bill != null && !billInfo.BillingMethod.Equals(bill)))
 {
      // Your code here
 }
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
JSR
  • 188
  • 8
  • Would you please explain why your solution solves the problem? – Quality Catalyst Jun 07 '17 at 21:18
  • NullReferenceException can occur if 'billInfo' is null. Only if it is not null, then – JSR Jun 08 '17 at 09:38
  • NullReferenceException can occur if 'billInfo' or 'BillingMethod' is null. So first checking for 'billInfo' not equal to null, then checking for other conditions. Also the condition after the '||' is otherway around.. as there is no point of checking not null if the first statement is failed – JSR Jun 08 '17 at 09:47