In previous chapters, we’ve examined the basic syntax you use when developing C# programs. Most of the code developed thus far has been relatively simple, focusing on basic construction techniques, such as creating classes, declaring fields and variables, and using properties. Beginning with this chapter, we’ll begin to use statements and expressions to build control structures in your programs.
In this chapter, you’ll see how using selection statements to control the flow of execution in a program allows you to write code that executes conditionally based on user input. There are two selection statements used in C#:
The if statement is used to execute blocks of code conditionally, based on the value of an expression that’s evaluated as your program executes.
The switch statement allows you to select from among multiple execution paths by matching the value of an expression with possible values, each of which has a code path associated with it.
This chapter also discusses the statements used to create iteration and looping algorithms in C#, as follows:
The for loop is used to perform a number of iterations over a statement or statement block. The for loop allows you to define the behavior of the loop in a compact format at the beginning of the loop.
The foreach loop has a simple structure and is designed for iterating over all members of a collection, such as an array or any of the collection classes in the Microsoft .NET Framework.
The while loop is used to repeat a statement or statement block for as long as an expression evaluates as true.
The do loop is similar to a while loop, except that it always executes at least once.
We’ll also look at jump statements, which are used to transfer control unconditionally to another part of your program. In previous chapters, you’ve seen and used return and throw statements. In this chapter, we’ll look at these statements in more detail and also examine the break, continue, and goto statements.