C# foreach Loop
In C#, the foreach
loop is a type of loop statement that is used to iterate over the elements in a collection or array. The foreach
loop can be used with any object that implements the IEnumerable
or IEnumerable<T>
interface. The syntax of the foreach
loop is as follows:
foreach (var item in collection) { // Code to execute for each item in the collection }
In this syntax, item
is a variable that is used to represent the current item in the collection, and collection
is the collection or array that you want to iterate over.
Here is an example that uses a foreach
loop to iterate over an array of strings:
string[] colors = { "red", "green", "blue" }; foreach (string color in colors) { Console.WriteLine(color); }
In this example, the foreach
loop iterates over the colors
array and assigns each string in the array to the color
variable. The code block inside the loop then prints out the value of color
. This continues until all elements in the array have been iterated over.
Note that the foreach
loop is read-only, which means you cannot modify the collection or array that you are iterating over. If you need to modify the collection or array, you should use a for
loop instead.