Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Current »

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 "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.

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 …

  • No labels