In c#, the Foreach loop is useful to loop through each item in an array or collection object to execute the block of statements repeatedly.
Generally, in c# Foreach loop will work with the collection objects such as an array, list, etc., to execute the block of statements for each element in the array or collection.
After completing iterating through each element in the collection, control will be transferred to the next statement following the foreach block.
In c#, we can use a break, continue, goto and return statements within the foreach loop to exit or continue to the next iteration of the loop based on our requirements.
Following is the syntax of defining the Foreach loop in the c# programming language.
If you observe the above syntax, we defined a foreach loop with the collection object and required variable names to access the collection object's elements.
Here, Type is a built-in data-type or custom class type, and var_name is a variable name to access elements from the collection object (Collection_Object) to use it in the foreach loop's body.
Following is the pictorial representation of the foreach loop process flow diagram in the c# programming language.
Now, we will see how to use the foreach loop in the c# programming language with examples.
Following is the example of using a foreach loop in c# programming language to iterate or loop through array elements.
If you observe the above example, we created a string array object “names” and looping through each element of array object using foreach loop and assigning array elements to string variable “name”.
To know more about arrays in the c# programming language, refer to c# arrays with examples.
When we execute the above c# program, we will get the result as shown below.
If you observe the above result, we loop through each element of the array and print those values on the console window based on our requirements.
Like c# foreach with arrays, we can use the foreach loop with the list object to process each element in the list object, but inside the foreach loop, it won’t allow us to modify (add or delete) the list object items.
To learn more about lists in c# programming, refer to c# lists with examples.
Following is the example of using a foreach loop in c# programming language to iterate or loop through list elements.
If you observe the above example, we used System.Collections.Generic namespace to access the List object and adding string elements to the list. We used foreach to loop through items in the list to print them on the console window.
When we execute the above c# program, we will get the result as shown below.
This is how we can use the foreach loop in the c# programming language to loop through each element in the array or collection objects based on our requirements.