-1

This may sound like a simple question but I have never used the || operator to check for NULL with another possible value. Is there a difference in how C# responds to:

if (a == "Hello" || a == null)

versus:

if (a== null || a == "Hello")
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • https://stackoverflow.com/questions/35301/what-is-the-difference-between-the-and-or-operators – Sweeper Mar 05 '18 at 18:05
  • In this simple case, no, but when you start checking an object's properties for `null`, then order would matter. If your object itself is null, and you don't check it before you access one of its properties, then you will get a `NullReferenceException`. – Kenneth K. Mar 05 '18 at 18:05

2 Answers2

3

It can make a difference.

The boolean operators short-circuit. If the first part of a boolean expression can determine the result of the entire expression, it will stop there. This won't matter so much for the exact sample in the question, but imagine you have this:

if (a.property == "hello" || a == null)

If a is null, that will throw an exception. This will not:

if (a == null || a.property == "hello")

You can also use the null-conditional and null-coalescing operators:

if (a ?? "hello" == "hello")

or

if (a?.property ?? "hello" == "hello")
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
-2

Is there a difference in how C# responds to ?

There is no difference in how C# responds, so order matters.

In this case, expressions are evaluated from left-to-right. So the second one is correct one semantically and safest choice under this condition.

if (a== null || a == "Hello") //check for null first
Tigran
  • 61,654
  • 8
  • 86
  • 123