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

Example

Result

if (4 > 3) Console.WriteLine("4 is greater than 3");

Will display "4 is greater than 3"

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 "4 is greater than 3"

and "If true statement is complete" for both false and true outcomes of the if statement. We really only wanted line 3 to be executed if the if statement was true. See next example.

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, "If statement is complete" will be printed whether the if() is is true or false.

But what about situations where it’s an either exclusively, in other words if this … else this …

In this example "4 is greater than 3" is printed followed by "If statement is complete". The converse would be true if the condition 4 < 3 were false, then output would be "4 is greater than 3" is printed followed by "If statement is complete".

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

Example

Result

In this example the following statements are printed in the order shown - "Some of other method", "4 is greater than 3", and lastly "If statement is complete".

In this example the following statements are printed in the order shown - "3 is NOT greater than 4", and lastly "If statement is complete".

Â