C# > Core C# > Control Flow > foreach Loop

foreach Loop with List of Objects

This snippet shows how to use a `foreach` loop to iterate over a list of custom objects and access their properties.

Code Snippet

This code defines a `Person` class with `Name` and `Age` properties. A `List` is created and populated with `Person` objects. The `foreach` loop iterates through the list, and for each `Person` object, it accesses the `Name` and `Age` properties and prints them to the console using string interpolation.

using System;
using System.Collections.Generic;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class ForeachObjectExample
{
    public static void Main(string[] args)
    {
        List<Person> people = new List<Person>()
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        Console.WriteLine("Iterating through the list of people:");

        foreach (Person person in people)
        {
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }
}

Concepts Behind the Snippet

This example showcases using `foreach` loop with a collection of objects, demonstrating how to access object properties within the loop. It leverages the power of C# classes and collections to manage data efficiently.

Real-Life Use Case

Imagine a scenario where you need to process a list of products, orders, or employees. You can use a `foreach` loop to iterate through the list and perform actions such as calculating totals, sending notifications, or generating reports for each item.

Best Practices

  • Ensure that the collection being iterated over is not null before entering the loop to avoid `NullReferenceException`.
  • Handle potential exceptions that might occur when accessing object properties within the loop.
  • Use descriptive names for object properties to improve code readability.

Interview Tip

Explain the importance of using strongly-typed collections like `List` when working with objects. This improves type safety and reduces the risk of runtime errors.

When to Use Them

Use this approach when you need to iterate over a collection of custom objects and perform operations that involve accessing object-specific properties.

Memory Footprint

The memory footprint is determined by the size of the collection and the size of each object within the collection. Consider using techniques like paging or lazy loading to handle very large datasets.

Alternatives

  • LINQ: LINQ provides a functional approach to querying and transforming collections of objects, often resulting in more concise and readable code.
  • Parallel.ForEach: For computationally intensive tasks, consider using `Parallel.ForEach` to distribute the processing across multiple threads, potentially improving performance.

Pros

  • Readability: Provides a clear and concise way to iterate over collections of objects.
  • Type safety: Ensures that the loop variable is of the correct type, reducing the risk of runtime errors.

Cons

  • Limited control: Less control over the iteration process compared to a traditional `for` loop.
  • Potential performance overhead: Can be slightly slower than a `for` loop in some cases, although the difference is often negligible.

FAQ

  • How can I filter the objects within the `foreach` loop?

    You can use an `if` statement within the loop to filter the objects based on specific criteria. Alternatively, you can use LINQ's `Where` method to filter the collection before iterating over it.
  • Can I modify the properties of the objects within the `foreach` loop?

    Yes, you can modify the properties of the objects within the loop. However, be careful not to modify the structure of the collection itself (e.g., adding or removing elements) as this can lead to unexpected behavior.