There are actually two different types of FOR loops included in C#. The first is the basic for iteration loop. The following code shows an example of a basic for iteration loop:

for(int i = 0; i < 100; i++)
{
Console.WriteLine(i.ToString());
}

Now, let’s dissect this a little bit so you can understand what’s going on here. The first thing done in this for loop is to declare the variable i as n integer and initialize it to 0. This is shown in the code above by “int I = 0”. This variable is often called the ITERATOR variable. The next piece is a comparison operation. As you should already know, comparison operations are Boolean operations that result in a true or a false. In this case, the comparison operation is represented by “i < 100”. This is telling the for loop to continue until the value of the variable i is equal to or greater than 100. Finally, “i++” tells the for loop to increment the value of i with each iteration. The only thing I haven’t explained is what’s contained within the for loop, “Console.WriteLine(i.ToString());”, this is the code to be executed on each iteration of the loop. In this case, we are outputting the value of i to the console window. Now that we’ve covered a basic for iteration loop, let’s take a quick peek at another for loop, the FOREACH iteration loop. Let’s say we have a list of integers:

List theList = newList();

Now we can write this:

foreach(List val in theList)
{
Console.WriteLine(val.ToString());
}

This is entirely different from the basic FOR iteration loop in that we aren’t declaring an iterator variable. This will parse through the entire list of integers one at a time and perform the necessary code on each. The benefit to the FOREACH loop is that we don’t have to determine how many elements are in the list, but we do have to have a list to parse through. The basic FOR loop doesn’t necessarily require a list to parse through, as is the case in the example I provided above. There is a caveat to be warned about when using a FOREACH loop. If you add or remove elements from within the list while it is being parsed by the FOREACH loop, it will cause an error. To avoid this error, anytime you know you will be modifying the list, you should use the basic FOR loop instead. Using our previous list of integers, the following is an example of this:

for(int i = 0; i < theList.Count; i++)
{
Console.WriteLine(theList[i].ToString());
theList.RemoveAt(i);
}

There are several things you’ll notice about this example that is slightly different from previous examples. First, instead of only going to 100, we’re getting a count of the elements from theList. This is to avoid certain potentially fatal memory leaks or errors. Secondly, we’re accessing the value using it’s index, which is shown by “theList[i]”. The variable i, in this case, is being used as the index value. NOTE: List<> used in this tutorial is a generic collection type found in System.Collections.Generic namespace.