DEV Community

loading...

C# Loops - Part 2 : For Each Loops

Grant
senior .net web developer, with interests in tech, android and learning new technologies.
・2 min read

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 string Name {get;set;}
public string Address {get;set;}
public string Tel {get:set}

public AddressBook ()
{
}
}

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. However there are some caveats.

  • You can't access instances within an object using indexing like the previous for loop. You know the list[1] syntax. This is because the IEnumerable class doesn't expose this functionality.

  • Thwre are some performance overheads with foreach loop, how it works behind the scenes. I won't get into it now but sometimes it can run slower than a for loop. But the pros can sometimes outweigh this.

  • Foreach loops make a copy od the object you're looping through. Therefore , amendments or assignments to the current item's properties is not feasible, i.e you cannot loop through a list and update all the values using a Foreach loop. You would need to use a for loop.

Well that's all I've got for now on foreach loops. Next up.. do while and while loops

Discussion (0)