0

pulling data from database I have this this

Result = main.Verified.Equals("1", StringComparison.OrdinalIgnoreCase) ? "Good Sale" : "Bad Sale";

Problem is that main.Verified is sometimes null and so it crashes with object reference error

What is an easy way to fix?

I was looking at this, but I'm not sure it has the best solution ?? Coalesce for empty string?

Community
  • 1
  • 1
  • if main.Verified is null do you consider it as "Good Sale" or "Bad Sale"? – Shai Aharoni Feb 22 '17 at 22:34
  • Technically, you are using a ternary. *not* a null coalescing operator – BradleyDotNET Feb 22 '17 at 22:34
  • @ShaiAharoni - null should not happen , it is bad data so think think Bad sale –  Feb 22 '17 at 22:45
  • @BradleyDotNET - thats right - thx –  Feb 22 '17 at 22:45
  • @JeremyMiller "Shouldn't happen" as in "there's an unfixed bug somewhere" or "shouldn't happen" as in "something unexpected happened"? If it's the first, then you **want** it to crash here (rather than just ignore the issue) and the solution is to fix the bug. If it's a "bad sale," is there some kind of sensible action that your program can do to fix the issue? – EJoshuaS - Stand with Ukraine Feb 22 '17 at 22:55

2 Answers2

4

Put the const value string first in the comparison.

Result = "1".Equals(main.Verified, StringComparison.OrdinalIgnoreCase) 
    ? "Good Sale" 
    : "Bad Sale";

This works because string.Equals() will always return false when compared with null. However, calling .Equals() on a null reference will always throw a NullReferenceException.

Silas Reinagel
  • 4,155
  • 1
  • 21
  • 28
  • ok, but I will never pull in "1" , so what can i do to first check for null? –  Feb 22 '17 at 22:46
  • 2
    You could write a more complex condition. `Result = (main != null && main.Verified != null && main.Verfified.Equals("1", StringComparison.OrdinalIgnoreCase)) ? "Good Sale" : "Bad Sale";` – Silas Reinagel Feb 22 '17 at 22:50
0

You could always do this:

Result =
    (main.Verified ?? "")
        .Equals("1", StringComparison.OrdinalIgnoreCase)
        ? "Good Sale"
        : "Bad Sale";
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • thanks I am also now hearing that per a business rule if it is null that i need to log it , so essentially if it is "1" is good, 2 -9 bad sale , and null is neither it gets some log to db or email or file ... –  Feb 23 '17 at 05:05