Sobes.tech
Junior — Middle

How does the foreach loop work and what does it do when iterating over a collection?

sobes.tech AI

Answer from AI

The foreach loop in C# is used to iterate over elements of a collection (such as an array, list, or any object implementing the IEnumerable interface). It automatically goes through each element of the collection, assigning it to a temporary variable, and executes the loop body for each element.

Example:

string[] fruits = { "apple", "banana", "cherry" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}

In this example, foreach sequentially outputs each fruit from the array. It is important to note that foreach does not modify the collection and does not require explicit index management, making the code cleaner and safer.

How does the foreach loop work and what does it do… - sobes.tech