For in C#
using System;
class Program
{
static void Main()
{
// The most basic type, with a single condition.
int i = 1;
while (i <= 3)
{
Console.WriteLine(i);
i = i + 1;
}
// A classic initial/condition/after for loop.
for (int j = 0; j < 3; j++)
{
Console.WriteLine(j);
}
// In C#, we can use a foreach loop to iterate over a sequence.
foreach (int k in Enumerable.Range(0, 3))
{
Console.WriteLine("range " + k);
}
// An infinite loop that will run until a break statement is encountered.
while (true)
{
Console.WriteLine("loop");
break;
}
// You can also continue to the next iteration of the loop.
foreach (int n in Enumerable.Range(0, 6))
{
if (n % 2 == 0)
{
continue;
}
Console.WriteLine(n);
}
}
}
C# provides several looping constructs. Here are some basic types of loops.
The most basic type is a while
loop with a single condition. It’s similar to the first example in the original code.
A classic for
loop in C# is identical to many other C-style languages, with initial, condition, and increment parts.
C# doesn’t have a direct equivalent to Go’s range
over an integer, but we can use foreach
with Enumerable.Range()
to achieve a similar effect.
An infinite loop in C# can be created with while (true)
. You can use break
to exit the loop or return
to exit the entire method.
The continue
keyword works the same way in C# as it does in many other languages, skipping to the next iteration of the loop.
To run this program, save it as Program.cs
and use the dotnet
command:
$ dotnet run Program.cs
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
C# offers other looping mechanisms as well, such as do-while
loops and more advanced foreach
loops for iterating over collections and other enumerable objects.