C# Tutorial - Dissecting Our Sixth Application – The Conditional if StatementThe conditional statement ‘if’, selects one of a number of possible statements for execution based on the value of a boolean expression. The ‘if’ statement comes in one of two forms: if( conditional test ) embedded statement or if( conditional test ) true embedded-statement else false embedded-statement Where:
This is best shown in a simple example: if( i >= 0 ) Console.WriteLine( "i is a positive number" ); else Console.WriteLine( "i is a negative number" ); So what does this mean? Simply put, it means that if the integer in the variable 'i' is greater than or equal to zero, then the application will write the line "i is a positive number" to the console. Otherwise the application will write the line "i is a negative number" to the console. Although the output is not technically correct, it shows how to use an ‘if’ statement. We can fix this allowing us to show nested ‘if’ statements. if( i >= 0 )
{
if( i > 0)
Console.WriteLine( "i is a positive number" );
else
Console.WriteLine( "i is zero" );
}
else
Console.WriteLine( "i is a negative number" );
In the above example, where the embedded-statement is more than a single line, curly braces must be used to denote the scope of the code to be executed. Shorthand NotationThe conditional statement ‘if .. else’ can be re-written in an alternative form for use in single line statements. (conditional test) ? true statement : false statement This is the same as the second version of the ‘if’ statement at the top of the page. This version can be useful for choosing which of two strings to display in a single line. ComparatorsIn the second version of the ‘if’ statement, the two 'if' statements have differing boolean comparators. As long as the conditional test evaluates to either a logical true or false, then any of a number of variations may be used. The following table lists the available symbols and there meanings:
Boolean LogicAs well as the set of comparators, the conditional test may include boolean logic operators. There are four logical operators that can be used.
When used in conjunction with comparators, any logic can be achieved within the conditional test.
|