4

Flow Control

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.

In this chapter, you look at two methods of controlling program flow, that is, the order of execution of lines of C# code. These two methods are:

  • Branching, where you execute code conditionally, depending on the outcome of an evaluation, such as “only execute this code if myVal is less than 10.”
  • Looping, or repeatedly executing the same statements (for 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. In this chapter you use it a lot, and so the chapter will start by discussing what is meant by Boolean logic so that you can use it in flow control scenarios.

In this chapter, you learn:

  • What Boolean logic is and how to use it.
  • How to control the execution of your code.

Boolean Logic

The bool type introduced in the last 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.

As an historical aside, it is worth remembering (and respecting) the English mathematician George ...

Get Beginning Visual C#® 2005 now with the O’Reilly learning platform.

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