C# Loop Constructs

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

Loop illustrated by arrow

Statements execute only once as control flow passes over them. Loop constructs manipulate the flow of control to repeat certain statements over and over again. They include the for, while, do while, and foreach loops. They are extensively used in C# programs.

Virtually every program spends most of its time in executing its loops. Aho et al., p 531
What can go wrong with a loop? Any answer would have to include incorrect or omitted loop initialization, omitted initialization of accumulators or other variables related to the loop, improper nesting, incorrect termination of the loop, forgetting to increment a loop variable.... McConnell, p. 373

For

For loop

As an introduction to looping in the C# language, this simple program writes the numbers zero through nine to the console with a for-loop. The int i variable is incremented each time after the body of the loop executes until the condition evaluates to false.

For
Program that uses for loop [C#]

using System;

class Program
{
    static void Main()
    {
	for (int i = 0; i < 10; i++)
	{
	    Console.WriteLine(i);
	}
    }
}

Output

0
1
2
3
4
5
6
7
8
9

While

While keyword

The while-loop is a very clear loop structure, but it can lead to infinite loops unless you are careful. We draw on research about the while-loop. Continuing on, the do-while loop is explored.

While Do While

Foreach

Foreach loop construct

The foreach-loop is probably the easiest and least error-prone loop in the C# language. We describe how you can use the foreach loop in various situations. Please also see the performance section below.

Foreach Foreach Reverse Loop DataTable Foreach Loop In Keyword

Statements

Goto keyword

There are several control statements you can use in the C# language with loops. The break statement and continue statements can be implemented with equivalent goto statements, but provide for clearer syntax.

Break Continue Goto

Empty statement. The C# language includes an empty statement construct, which is a simple semicolon after nothing. The empty statement is often used in loops, as shown here.

Empty Statement

Note: The empty statement is my favorite statement of all the statements.

Yield keyword

Yield. One feature that is unique to the C# language is the yield keyword. This implements a feature that allows the position in the control flow to be remembered and resumed when the statement finishes. The yield keyword is implemented in terms of simpler constructs in the lower-level intermediate language.

Yield IEnumerable Array Example

Strings

String type

It is common to need to loop over strings or the characters in strings in your C# programs. We show how to loop with string data, providing practical examples.

Loop Over String Array Loop Over String Chars String For-LoopPerformance optimization

Performance

One favorite topic of mine is how to make loops go faster. After all, shaving nanoseconds off of your program's runtime should always be at the top of your priority list. We mainly describe classic techniques for code tuning your loops.

Decrement Loop Optimization For Versus Foreach Performance Foreach Loop Optimization Loop Jamming Loop Unwinding int i Induction Variable

Note: Actually, shaving nanoseconds off your program's runtime should not be always at the top of your priority list. Something more reckless should clearly be ranked higher—please use your imagination.

Misc.

Loops are a great way to improve spaghetti code—code that is very hard to follow due to unusual flow control. Loops can impart structure and sense to your code.

Loop Over Two Variables Spaghetti Code

Summary

The C# programming language

Nearly every C# program will use loops. Nearly all the processor time in your C# programs will be spent in loops. It follows, then, that loops—primarily the for, while, and foreach loops—are something that is important to study and research: they prove essential to many aspects of development.

Dot Net Perls