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.
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.
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.
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.
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.
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").
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With