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

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com code downloads for this chapter at www.wrox.com/remtitle.cgi?isbn=9781118314418 on the Download Code tab. The code is in the Chapter 4 download and individually named according to the names throughout the chapter.

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 “Execute this code only 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. In this chapter, you’ll use it a lot, so the chapter begins by discussing what is meant by Boolean logic, and then goes on to cover how you can use it in flow control scenarios.

BOOLEAN LOGIC

The bool type introduced in the previous chapter can hold one of only ...

Get Beginning Visual C# 2012 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.