DEV Community

Cover image for C# Loops - Part 2 : For Each Loops
Grant Riordan
Grant Riordan

Posted on • Edited on

C# Loops - Part 2 : For Each Loops

For Each Loops

The For Each Loop in concept works like any other loop in that it iterates over an object a number of times. However in a Foreach loop it will go from the first item all the way through to end in sequence. Unless, you manipulate the sequence by skipping items using the continue keyword.

How does it work ?

The foreach loop can iterate over any object that inherits from the IEnumerable class (e.g lists, collections).

As already mentioned, it does this in order of the list, i.e order the items were loaded in / added to the list (or ordered). It does this because it iterates over the instances of the list. An instance is a concrete occurrence of any object, existing usually during runtime, from memory.

Example:

var names = new List<string>();
names.Add("Grant", "Barry", "Jenny”,"Shaun");

foreach(var name in names)
{
  Console.WriteLine(name);
}

//Output
Grant
Barry
Jenny
Shaun
Enter fullscreen mode Exit fullscreen mode

I'll show you an example of a object with more properties.

public class AddressBook
{
    public AddressBook()
    {
    }

    public string Name { get; set; } = string.Empty;
    public string Address { get; set; } = string.Empty;
    public string Tel { get; set; } = string.Empty;  
}
Enter fullscreen mode Exit fullscreen mode
var addresses = AddressBook();
addresses.Add(
     new Address{
       Name = "Grant"
       Address = "Developer Avenue, DevTown"
       Telephone = "019286661"
     },
     new Address{
       Name = "Terry"
       Address = "5 Developer Avenue, DevTown"
       Telephone = "019286662"
     });

foreach (var address in addressBook){
  Console.WriteLine(address.Name);
  Console.WriteLine(address.Tel);
}

//Output
Grant
019286661
Terry
019286662
Enter fullscreen mode Exit fullscreen mode

That's how you can use the For Each loop.

Caveats of foreach

While foreach is simpler to read than for, there are a few things to keep in mind:

No indexing

You can’t directly access items with list[1] inside a foreach. That’s because foreach works on IEnumerable, which doesn’t expose indexes.

Performance

A foreach loop has a small overhead compared to a for loop. In most cases this won’t matter, but in performance-critical code, for may be faster.

Modifying items

foreach gives you a copy of the current item, not a direct reference. That means you can’t reassign values to the list items inside the loop.

✅ You can read properties.

❌ You can’t update the items themselves (use a for loop for that).

That’s all for foreach — next up → while and do while loops.

Top comments (0)