A Beginner's Guide to Foreach Loop in C# - Examples Included

Category > CSHARP || Published on : Friday, March 10, 2023 || Views: 150 || C# foreach loop collection array beginner's guide.


In C#, foreach loop simplifies the process of looping through a collection or an array by providing a concise syntax that eliminates the need for index variables and reduces the chances of errors.

Introduction:

In C#, foreach loop is used to iterate through a collection or an array. It simplifies the process of looping by providing a concise syntax that eliminates the need for index variables and reduces the chances of errors.

Syntax:

The syntax for a foreach loop in C# is as follows:

foreach (var item in collection)
{
    // Statements to execute
}

Here, var is a keyword that specifies the type of the element in the collection, and item is a temporary variable that is used to hold the current element in each iteration. The collection is the object that contains the elements to be iterated.

Example:

Let's take an example of a foreach loop to iterate through an array of integers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int num in numbers)
{
    Console.WriteLine(num);
}

In this example, we have an array of integers called numbers. The foreach loop iterates through each element in the array and assigns it to the variable num. Then, the Console.WriteLine method is called to output the value of num to the console.

Output:

1
2
3
4
5

In the above example, the keyword int is used to specify the type of the elements in the array. If the array contains objects of another type, such as strings, the keyword should be replaced accordingly.

Important Points to remember:

  • The collection being iterated must implement the IEnumerable interface, which defines a method called GetEnumerator that returns an object that implements the IEnumerator interface. This object is used to iterate through the elements in the collection.

  • The foreach loop is read-only, meaning that the elements in the collection cannot be modified while the loop is executing.

  • The break and continue keywords can be used within a foreach loop to exit the loop or skip to the next iteration, respectively.

  • If the collection is null, an exception of type ArgumentNullException will be thrown.

Conclusion:

In conclusion, the foreach loop in C# is a powerful and efficient way to iterate through collections and arrays. It provides a concise and easy-to-read syntax that eliminates the need for index variables and reduces the chances of errors. By keeping these important points in mind, you can effectively use foreach loops in your C# code to iterate through any collection or array.