foreach loop 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: for loop c#
for(int i = 0; i < 3; i++)
{
Console.WriteLine("Hi");
}
for(int i = 0; i < 3; i++)
{
Console.WriteLine(i);
}
for(int i = 5; i <= 8; i++)
{
Console.WriteLine(i);
}
for(int i = 3; i > 0; i--)
{
Console.WriteLine(i);
}
for(;;)
{
}
Example 3: 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 4: how do i foreach c#
foreach (string element in fibNumbers)
{
Console.WriteLine(element.HelloWorld);
}
Example 5: get out of foreach statement c#
foreach (string s in sList)
{
if (s.equals("ok"))
{
break;
}
}
Example 6: The foreach Loop c#
string[] names = {"William.", "James", "Oliver", "Lucas"};
foreach (string i in names)
{
Console.WriteLine(i);
}