C# includes a rich set of statements that are used to control the flow of execution in your code. These statements fall into three categories:

  • Selection statements (if and switch)  Used to select a statement or statement block to be executed. These statements are used to select from among multiple paths of execution. The if statement is typically used to execute statements if a specific condition evaluates as true. The if statement is optionally coupled with the else statement in order to force a selection from one of two possible execution paths. Although the switch statement can be used to select from one or two possible execution paths, it’s most often used when there are more than two possible execution branches.

  • Iteration statements (for, foreach, while, and do)  Used to build loops. Each of these loops has different characteristics that make it more or less useful in specific situations. The for loop is most useful when statements must be executed a specific number of times; the foreach loop is used to iterate over each item in a collection. The while loop executes statements for as long as a controlling expression evaluates as true; the do loop is similar to the while loop but guarantees that the controlled statements execute at least once.

  • Jump statements (break, continue, goto, return, and throw) Used to transfer control to a new location in your program. The break and continue statements are used only with control structures. The break statement is used to transfer control out of the current control structure. The continue statement is used to immediately return to the beginning of a loop statement. The return statement is used to transfer control to the invoker of the method, and the throw statement is used to raise an exception. C# also includes the notorious goto statement, which can be used to transfer control to a label within the current method.

Selection and iteration statements use the values of expressions to control their execution. (Expressions are discussed in Chapter 4.) Jump statements transfer control unconditionally.

Chapter 6 discusses additional C# language features that are used to structure your code: delegates and attributes. Delegates are similar to function pointers used in C++ and other languages, with additional type-safety features. Attributes are a convenient way for you to declaratively add functionality to your application and are widely used to add support for transactions, security, and other runtime features.

Part III: Programming Windows Forms