2.7. Loops

Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops. You choose the type of loop based on the type of task you need to perform. Your choices are as follows:

  • You can loop a set number of times with a for loop.

  • You can loop through all the items in a collection of data using a foreach loop.

  • You can loop while a certain condition holds true, using a while loop.

The for and foreach loops are ideal for chewing through sets of data that have known, fixed sizes. The while loop is a more flexible construct that allows you to continue processing until a complex condition is met. The while loop is often used with repetitive tasks or calculations that don't have a set number of iterations.

2.7.1. The ...

Get Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional, Second Edition now with O’Reilly online learning.

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