If statement
The if statement selects another statement for execution based on the output value of a boolean expression.
It’s basic form is
if(
<boolean expression> )
<statement to execute if the boolean expression is true>
Example | Result |
---|---|
if (4 > 3)
Console.WriteLine("4 is greater than 3"); | Will display There is only one statement following the if expression |
if (4 > 3)
Console.WriteLine("4 is greater than 3");
Console.WriteLine("If true statement is complete"); | Will display and |
if (4 > 3)
{
Console.WriteLine("4 is greater than 3");
Console.WriteLine("If true statement is complete");
} | The curly braces create a code block. Everything within that code block is treated as a single statement. The opening curly brace “{“ can be placed on the same line as the if statement. it’s a matter of preference of style. Notice that the statements within the code block are aligned slightly to the right. This is convention and makes it easier to read the code. |
In this example, But what about situations where it’s an either exclusively, in other words if this … else this … | |
In this example |
Compound logical expressions
How does C# handle logical expressions that comprise two or more expressions? Well, it depends on the logical operator.
The && (logical AND) operator is known as the short circuit operator. The operator has two operands left hand (lh) and right hand (rh). The && operates such that if the lh fails (is false) then the rh is not evaluated. However, if the lh should pass (is true) then the rh must also be evaluated.
Example | Result |
---|---|
In this example the following statements are printed in the order shown - | |
In this example the following statements are printed in the order shown - |
Â