6

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
}

5 Answers 5

8

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

msdn

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.