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")
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")
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")
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