Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

<statement to execute if the boolean expression is true>

Example

Result

Code Block
languagec#
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

Code Block
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.

Code Block
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.

Code Block
if (4 > 3)
{
    Console.WriteLine("4 is greater than 3");
}
Console.WriteLine("If statement is complete");

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 …