Decisions and Branching
Changing the flow of control in a program in response to some kind of input or calculated value is an essential part of a programming language. C# provides the ability to change the flow of control, either unconditionally, by jumping to a new location in the code, or conditionally, by performing a test.
The simplest form of conditional branching uses the if construct. You can use an else clause with the if construct, and if constructs can be nested.
Unlike C and C++, if statements require Boolean values. For example, it is not permissible to have a statement that doesn't get evaluated to a simple True or False, such as (a=10). In C#, 0 cannot be substituted for False and 1, or any other value, for True.
The statements following the if and else keywords can be single lines of code as shown in the first if-else statement in the previous code example, or a block of statements contained in braces as shown in the second if-else statement. It is permissible to nest if-else statements, but it is usually considered better programming practice to use a switch statement instead.
A switch statement can perform multiple actions depending on the value of a given expression. The code between the case statement and the break keyword is executed if the condition is met. If you want the flow of control to continue to another case statement, use the goto keyword.
The expression that the switch statement uses to determine the case to execute must use the Built-in Data Types, such as int or string; you cannot use more complex user-defined types.
Unlike Visual Basic, in C# the condition must be a constant value. For example, it is not permissible to compare the expression to a range of values.