foreach is a looping statement :
- repeats a group of statements for each element in an array or an object collection. (or)
- used to iterate through the collection/ an array to get the required information.
Advantages:
- Easy implementation.
- Least possibility of errors. [ especially when working with index based values, like in arrays. ]
Syntax:
foreach(<datatype of collection / array> <variablename> <in> <collection/array>)
{
code....
}
Example:
foreach(string courseName in coursesList)
{
code....
}
- here, coursesList is a string collection
- string courseName is called as the "loop variable" which represents the element from the collection in each iteration.
- in is the pre-defined keyword
Working style of foreach loop:
- data type of loop variable must and should be the same as the data type of the array/collection that has to be referred.
- At the time of execution, first the foreach loop goes to the array/collection, counts the number of elements & repeats the loop that many times automatically.
- At each iteration array/collection location value will be copied into loop variable.
Example 1: In the below example, we'll see how to iterate a group of int type array elements using foreach loop.
Example 2: In the below example, we'll see how to iterate a group of values in a collection.
NOTE : in .NET we've different types of collections. For example we took "List" a generic collection