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 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.