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. |
if (4 > 3) { Console.WriteLine("4 is greater than 3"); } Console.WriteLine("If statement is complete"); | In this example, But what about situations where it’s an either exclusively, in other words if this … else this … |