Reputation: 3997
I read that the AND operator &&
in .NET conditionally evaluates its second argument.
Is it safe to check for null and then check some field within a single statement?
For example, imagine we have a class SomeClass, which has an integer field Id:
class SomeClass
{
public Int32 Id { get; set; }
}
Then, we receive an object of this type somewhere and try to perform some actions on it:
public void SomeMethod(SomeClass obj)
{
if (obj != null)
if (obj.Id == 1)
{
// do some actions
}
}
Can we rewrite this as follows to reduce the amount of code? Will the null-check be safe?
public void SomeMethod(SomeClass obj)
{
if (obj != null && obj.Id == 1)
// do some actions
}
Upvotes: 6
Views: 3906
Reputation: 36176
yes, thats simple logic, if among several AND statments, one is false, there is no need to keep evaluating them because the result will be FALSE, so the compiler stops the evaluation when the first FALSE is found
Upvotes: 1
Reputation: 223422
The term here is "short-circuit". With and (&&)
operator, if the first condition fails, it will not continue with the next condition. They way you are doing is not only save it is the correct way to do.
7.11 Conditional logical operators - C# Reference MSDN
The && and || operators are called the conditional logical operators. They are also called the "short-circuiting" logical operators.
Upvotes: 1
Reputation: 12942
Yes... This is safe in C# and many other languages. If the program knows that the following checks can't make the entire if statement become true there is no need to even look at them.
This type of evaluation is called Lazy Evaluation.
Upvotes: 1
Reputation: 60493
Yes it will be safe, && conditions are treated from "left to right", if the first doesn't match in your case, the second won't be evaluated
The operation
x && y
corresponds to the operation
x & y
except that if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation.
Upvotes: 8
Reputation: 37232
Yes, that is absolutely safe to do.
As you state in your question, if the object is null, only the first condition is evaluated, so the second condition (which would raise a NullReferenceException) is never executed. This is known also as "short-circuit" evalation.
Upvotes: 3