foreach loop in c# code example

Example 1: how to make a for loop in c#

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Value of i: {0}", i);
}

Example 2: foreach syntax c#

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Example 3: how do i foreach c#

//No counter just the foreach.
 //the HelloWorld is the Class objects name nor a public string can be used aswell.
foreach (string element in fibNumbers)
{
    Console.WriteLine(element.HelloWorld);
}

Example 4: get out of foreach statement c#

foreach (string s in sList)
{
    if (s.equals("ok"))
    {
        break; // get out of the loop
    }
}

Example 5: The foreach Loop c#

string[] names = {"William.", "James", "Oliver", "Lucas"};
foreach (string i in names) 
{
  Console.WriteLine(i);
}

Example 6: c# foreach

var numbers = new NumberList<int> { 0, 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    DoSomething();
}

Tags:

Misc Example