C# > Core C# > Control Flow > foreach Loop
Basic foreach Loop Example
This snippet demonstrates a basic `foreach` loop in C# used to iterate through elements of an array.
Code Snippet
This code initializes a string array called `names`. The `foreach` loop iterates through each string element in the `names` array. In each iteration, the current string element is assigned to the `name` variable, and its value is printed to the console.
using System;
public class ForeachExample
{
public static void Main(string[] args)
{
string[] names = { "Alice", "Bob", "Charlie" };
Console.WriteLine("Iterating through the names array:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
Concepts Behind the Snippet
The `foreach` loop is designed to iterate over collections that implement the `IEnumerable` or `IEnumerable
Real-Life Use Case
Consider processing a list of customer objects, retrieving data from a database, or handling files in a directory. The `foreach` loop is ideal for iterating through the results of these operations to perform actions on each item.
Best Practices
Interview Tip
Be prepared to explain the difference between `foreach` and `for` loops. Highlight that `foreach` is designed for iterating over collections without needing to manage indices, while `for` loops provide more control over the iteration process.
When to Use Them
Use `foreach` when you need to iterate over all elements in a collection and don't require access to the index of each element. If you need to modify the collection during iteration or need access to the index, consider using a `for` loop.
Memory Footprint
The `foreach` loop is generally memory-efficient as it iterates through the collection without creating unnecessary copies. However, if the collection is very large, consider using streaming techniques to process data in chunks to avoid loading the entire collection into memory at once.
Alternatives
Pros
Cons
FAQ
-
What happens if the collection is empty?
If the collection is empty, the `foreach` loop will simply not execute its body. The code will continue execution after the loop without any errors. -
Can I break out of a `foreach` loop?
Yes, you can use the `break` statement to exit the `foreach` loop prematurely. When `break` is encountered, the loop terminates, and execution continues with the next statement after the loop. -
Can I use `continue` in a `foreach` loop?
Yes, you can use the `continue` statement to skip the rest of the current iteration and move to the next element in the collection.