Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

}

Will result in:

9

10

Note: Continue is often most useful in while or do-while loops. For-loops, with well-defined exit conditions, may not

benefit as much.

Section 28.7: While loop

int n = 0; while (n < 5)

{

Console.WriteLine(n); n++;

}

Output:

0

1

2

3

4

IEnumerators can be iterated with a while loop:

//Call a custom method that takes a count, and returns an IEnumerator for a list

//of strings with the names of theh largest city metro areas.

IEnumerator<string> largestMetroAreas = GetLargestMetroAreas(4);

while (largestMetroAreas.MoveNext())

{

Console.WriteLine(largestMetroAreas.Current);

}

Sample output:

Tokyo/Yokohama

New York Metro

Sao Paulo

Seoul/Incheon

Section 28.8: break

Sometimes loop condition should be checked in the middle of the loop. The former is arguably more elegant than the latter:

for (;;)

{

GoalKicker.com – C# Notes for Professionals

123

// precondition code that can change the value of should_end_loop expression

if (should_end_loop) break;

// do something

}

Alternative:

bool endLoop = false; for (; !endLoop;)

{

// precondition code that can set endLoop flag

if (!endLoop)

{

// do something

}

}

Note: In nested loops and/or switch must use more than just a simple break.

GoalKicker.com – C# Notes for Professionals

124