Chapter 4. Flow Control

WHAT YOU WILL LEARN IN THIS CHAPTER

  • Boolean logic and how to use it

  • How to branch code

  • How to loop code

All of the C# code you've seen so far has had one thing in common. In each case, program execution has proceeded from one line to the next in top-to-bottom order, missing nothing. If all applications worked like this, then you would be very limited in what you could do. This chapter describes two methods for controlling program flow—that is, the order of execution of lines of C# code: branching and looping. Branching executes code conditionally, depending on the outcome of an evaluation, such as "only execute this code if the variable myVal is less than 10." Looping repeatedly executes the same statements, either a certain number of times or until a test condition has been reached.

Both of these techniques involve the use of Boolean logic. In the last chapter you saw the bool type, but didn't actually do much with it. This chapter uses it a lot, so the chapter begins by discussing what is meant by Boolean logic so that you can use it in flow control scenarios.

BOOLEAN LOGIC

The bool type introduced in the previous chapter can hold one of only two values: true or false. This type is often used to record the result of some operation, so that you can act on this result. In particular, bool types are used to store the result of a comparison.

Note

As a historical aside, it is the work of the mid-nineteenth-century English mathematician George Boole that forms the basis ...

Get Beginning Visual C# 2010 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.