C# Tutorial - 08 - Conditionals


Uploaded by ProgrammingVideos on 14.01.2010

Transcript:
In this section we'll look at the conditional statements in C#, which are used to execute
different code blocks based on different conditions. The if statement will execute only if the
expression inside the parenthesis is evaluated to true. It can include any of the comparison
and logical operators. To test for other conditions we can extend
the if statement with any number of else if clauses.
Each additional condition will only be tested if all previous conditions are false.
The if statement can also have one else clause at the end, which will execute if all previous
conditions are false. As for the curly brackets, they can be left
out if we only need to execute a single statement conditionally.
Next we have the switch statement which checks for equality between either an integer or
a string and a series of case labels, and then passes execution to the matching case.
It may contain any number of case clauses and it can end with a default label for handling
all other cases.
Note that the statements after each case label ends with the break keyword to break out of
the switch. Unlike many other languages the cases in C#
must end with a jump statement, such as break. This means that we cannot leave out the break
keyword to allow the execution to fall-through to the next label. The reason for this is
because unintentional fall-throughs is a common programming error. If we actually want to
fall-through we have to explicitly show this using the goto jump statement followed by
a label, which will cause the execution to jump to that label. Goto can also be used
outside of the switch, but it's strongly discouraged since it can quickly become difficult to follow
the flow of execution.
In addition to the if and switch statements there's the ternary operator that can replace
a single if/else clause when it assigns values to a specific variable. This operator takes
three expressions. If the first one is evaluated to true the second expression is returned
and if it's false the third one is returned.