Loops are very common when you are programming. They are used to iterate through a list or array or run until a certain condition has been reached. There are different kinds of loops and this time I want to show you all about the foreach in C#.
Things you should know
For this tutorial you need to know or have the following terms/techniques:
- General C# and .NET knowledge
I am using .NET 6 for this tutorial. - Visual Studio 2022 or higher
Table Of Contents
What is the foreach loop?
The foreach loops through a list or array, we call that an iterable-item. With the foreach, you assign a variable to the iterable-item that represents a single item in that iterable-item. We call that an element. In each loop, the element is a representation of an item in the iterable-item. It starts with the first (index 0) and with the next loop its the second item (index 1), and so forth.
A foreach looks like a for loop, but a for loop has different statements and can be run with a different condition. A foreach always looks the same:
The foreach always starts with foreach and has two elements:
- The element represents an item from the iterable-item. It should be declared as the same type.
- The iterable-item is an object that is defined by the IEnumerable, which makes it a list. Think for example about a dictionary, list, array, and much more.
Examples
Below are some examples that show how the foreach in C# works
Basic example
In the foreach, I first declare the type and name for the element. After that, I, place in and then the iterable-item, which is, in this case, a List<string>. In the body of the foreach, I can use the title (the element) to print the name of the movie on the screen.
It can also be use with a list of objects, as shown below:
Stopping / Break
In some cases, you might want to stop or abort the foreach before the condition is met. You can do this with break. In the example below, the while loop will stop as soon as the element title equal “Inception”.
Next iteration / Continue
In some cases, you want to skip some of the code and continue to the next run/iteration. This can be achieved by using the continue. In the example below, “Inception” won’t be printed on the console.
Related posts:
No related posts.