C# foreach Loop
The C# foreach loop is another loop, which doesn’t include initialization, condition, increment/decrement characteristics just like other loops. Foreach loop uses a collection of elements and processes them. It evaluates each element of collection individually and returns. No index is required by this loop for processing. Since, with no indexes, loops are much easier to use.
Foreach loop is considered to be much easier to use and least error-prone.
The basic syntax of foreach C# is
foreach (data-type loop_variable_name in collection_name)
{
// loop body
}
foreach is a reserved word we use to declare foreach loop.
data-type should be same as of data-type of the collection.
loop_variable_name is variable to be which we can use in a loop.
collection_name is the name of the collection or array which the foreach loop will iterate.
Example Program
using System; namespace for_each { class Program { static void Main(string[] args) { // initializing array string[] my_arr = new string[] { "User 1", "User 2", "User 3"}; //retrieving values from array using foreach loop foreach (string name in my_arr) { Console.WriteLine("This is " + name); } } } }
As it is clear from the example above that we didn’t use indexes to iterate through an array. The data type used for loop variable name is the string as it is same for my_arr.
Below is another example using an integer array. In this example, we set the data type of loop variable to int as this loop will iterate through an integer array.
Example Program
using System; namespace for_each { class Program { static void Main(string[] args) { // initializing array int [] my_arr = new int[] { 1, 2, 3, 4, 5}; //retrieving values from array using foreach loop foreach (int element in my_arr) { Console.WriteLine("This is no " + element); } } } }
From both above examples, we can see that foreach C# doesn’t use indexes to iterate through the arrays.
Nested foreach C#
Just like the other loops available in c#, we can nest the c# foreach loop as well. i.e. a foreach loop(s) inside foreach and other loops. We can have any number of loops inside other loops.
Example program
using System; namespace for_each { class Program { static void Main(string[] args) { // initializing array int [] my_arr = new int[] { 1, 2}; int [] my_array = new int[] { 6, 7, 8, 9, 10}; //retrieving values from array using foreach loop foreach (int outer_element in my_arr) { Console.WriteLine("This is Outer no " + outer_element); foreach (int inner_element in my_array) { Console.WriteLine("This is Inner no " + inner_element); } } } } }
As like other loops, the compiler will execute the inner foreach loop for every iteration of the outer foreach loop. Comparison example between for and foreach loop can be seen here.
Note:- It is not necessary to nest foreach loop inside a foreach loop only. We can nest any loop inside any of the loops available in c#.
One thought on “C# foreach loop”