Home » C# Tutorial » Everything You Need to Know About C# Foreach:

Everything You Need to Know About C# Foreach:

Be it an industry or expert or a complete fresher right out of school, we must admit, one of the things that makes C# one of the most versatile programming languages in the world is the fact that it has useful functions for every task. It lets the coder customize the code to substitute manual coding with short functions, which not only saves time but also makes coding with C# that much more interesting. One of those helpful functions, that we will be learning about in this article, is the C# foreach loop. So, without any further ado, let us jump right in.

What is a C# Foreach Loop?

A Foreach loop in C# is for-loops designed to allow the developer or coder to work with collections of data. As we may already know, an array is a collection of data and we can loop through this array by using a foreach loop. It can also be defined as a loop inside C# that allows us to easily work with the elements of a list. 

Using a for loop will make it easier for the programmer or coder to manipulate and change the different elements of an array or a list, but things get a little different with the C# foreach loops. The main purpose of a foreach loop is to go through each element of an array or list from start to finish, one by one.

Usage of the foreach loops is ideal for accessing and reading the elements of a list, loop, or array, but not so much updating the elements.

How to use a C# Foreach Loop?

In C#, the method of using a foreach loop is pretty similar to that of a for loop. They are not exactly the same as the elements in their syntax differ. The syntax for a basic foreach loop looks a little something like the following:

Foreach (type element in collection)
{
statement;
statement;
}

Let us break this syntax down to better understand how the foreach loops function in C#.

The ‘type’ and ‘in’ keywords within the aforementioned syntax are known as reserved keywords as they serve a set of reserved functions within the foreach system. The ‘type’ keyword may be replaced by ‘int’ or even ‘var’ but they all are used to essentially do the same purpose, i.e., to declare a single element within a given array or list.

The ‘in’ keyword needs to be followed by the array, loop, or list in question. Whichever array, loop or list the developer wishes to manipulate elements from, they will declare it after the ‘in’ reserved keyword. The ‘collection’ placeholder is meant to serve as a proxy array. That is the spot where you will add the name of the array, list, or loop that you want to use.

The ‘element’ placeholder is reserved for the name of the variable that you desire. This can be anything the programmer or developer wished to associate with the variable that they wish to work with. The following diagram will aid in comprehending how the flow of C# foreach loop functions.

C# Foreach Examples:

As we may have guessed already, C# Foreach Loops are very dynamic in nature. As opposed to some other functions within C#, foreach loops can be used with multiple concepts to ease the programmers’ way through the program. Let us start with a basic C# foreach formation. 

Basic Foreach Formation:

Let us first get acquainted with the simplest form of the foreach loop. As mentioned earlier, it accessed each element in a collection (array, loop, or list) one after the other. This collection usually implements the IEnumerable interface. As opposed to the classic for loop that lets you modify specific elements, the foreach loop does not use indexes, and therefore, does not provide much control over the individual items in that collection.

using System;
using System.Collections.Generic;
 
class MainClass {
  public static void Main
  (string[] args) {
    
    var countries = new List<string>() { "America", "India", "Japan", “China” };
foreach (string country in countries)
{
    Console.WriteLine(country);
}
  }
}

OUTPUT:

America
India
Japan
China

As you can see from the above example, the foreach loop reads and accesses each element of the list ‘countries’ as an individual unit.

Now that we have an idea of how the foreach loop works in its simplest form, let us take a look at its different iterations.

Break with Foreach Loops:

Since foreach loops are dynamic in nature, even break statements can be used with them. Within an if statement, if it is satisfied and the programmer has mentioned a break within it, the foreach loop ignores the rest of the collection and exits the loop body. For instance,

using System;
using System.Collections.Generic;
 
class MainClass {
  public static void Main
  (string[] args) {
    
    var countries = new List<string>() { "America", "India", "Japan", "China" };
foreach (string country in countries)
{
    if (country == "Japan")
    {
        break;
    }
    Console.WriteLine(country);
}
Console.WriteLine("End");
  }
}

OUTPUT:

America
India
End

Continue with Foreach Loops:

Like the previous example with the break statement within a foreach loop, if a continue statement is used within a foreach loop, then it will automatically skip the specified item and continue with the rest of the collection. For example,

using System;
using System.Collections.Generic;
 
class MainClass {
  public static void Main
  (string[] args) {
    
   var countries = new List<string>() { "America", "India", "Japan", "China" };
foreach (string country in countries)
{
    if (country == "Japan")
    {
        continue;
    }
    Console.WriteLine(country);
}
  }
}

OUTPUT:

America
India
China

“Yield Return” with Foreach Loops:

Since C# has introduced the ‘yield return’ statement, we can use that with foreach loops as well. The application of yield return statements with C# foreach loops is extremely simple. All you need to do is create a property or method with the return type “IEnumerable”. In the middle of this method, a ‘yield return’ statement can be called for every element you wish to include in the collection or array.

using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static void Main()
    {
        foreach (var digit in Get().Take(2))
        {
            Console.WriteLine(digit);
        }
    }
 
    static IEnumerable<int> Get()
    {
        foreach (var digit in new[] { 5, 6, 7 })
        {
            yield return 5;
yield return 6;
yield return 7;
        }
    }
}

OUTPUT:

5
6
7

And just like that, you know all there is to know about starting off with C# foreach loops. With practice and constant application, you can explore the different areas in which you can use foreach loops for multiple purposes. Foreach loops are a time and effort saving function that many programmers use regularly. With constant practical applications, you can get there too. Happy learning!

Do you know?
1. C# Enum
2. C# Dictionary
3. C# Switch Case
4. C# Substring
5. C# Foreach

Pin It on Pinterest