Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chained IF structure

Tags:

java

c#

Imagine this case where I have an object that I need to check a property. However, the object can currently have a null value.

How can I check these two conditions in a single "if" condition?

Currently, I have to do something like this:

if (myObject != null)
{
    if (myObject.Id != pId)
    {
        myObject.Id = pId;
        myObject.Order = pOrder;
    }
}

I would like something like this:

if (myObject != null && myObject.Id != pId)

I want to evaluate the second condition only if the first was true.

like image 317
Nelson Reis Avatar asked Dec 17 '08 14:12

Nelson Reis


People also ask

What is a chained if statement?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.

What does a nested IF structure mean?

One IF function has one test and two possible outcomes, TRUE or FALSE. Nested IF functions, meaning one IF function inside of another, allows you to test multiple criteria and increases the number of possible outcomes.

What is a chained conditional in programming?

Chained conditionals are simply a "chain" or a combination or multiple conditions. We can combine conditions using the following three key words: - and. - or. - not.

Which statement is also known as chained conditional statement?

Python provides an alternative way to write nested selection such as the one shown in the previous section. This is sometimes referred to as a chained conditional. The flow of control can be drawn in a different orientation but the resulting pattern is identical to the one shown above.


3 Answers

if (myObject != null && myObject.Id != pId)
{
   myObject.Id = pId;
   myObject.Order = pOrder;
}

&& is a short-circuiting logic test - it only evaluates the right-hand-side if the left-hand-side is true. Contrast to a & b, which always evaluates both sides (and when used with integral types instead of bool, does a bitwise "and").

like image 180
Marc Gravell Avatar answered Oct 10 '22 02:10

Marc Gravell


It should be stressed that the short-circuited evaluation of the && in the if() is absolutely guaranteed by the language standards (C, C++, Java and C#). It's been that way since the first edition of K&R's "C Programming Language".

It's not something that you have to worry "Does my compiler implement this?". If definitely does.

like image 30
James Curran Avatar answered Oct 10 '22 02:10

James Curran


if (myObject != null && myObject.Id != pId)
{
//bla
}

this is safe because operator && is evaluated lazily, meaning that if the LHS is false, the RHS is never evaluated

like image 43
spender Avatar answered Oct 10 '22 01:10

spender