Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# for loop with already defined iterator

Tags:

c#

I want to make a loop using an already-defined iterator.

At present I am using

int i;
while (i<10)
{
    Console.Writeline(i);
    i++;
}

This is ugly because someone else might later remove the i++. If it is separated from the while statement by a large block of code, it will not be clear what it is for.

What I'd really like is something like

int i;
for (i<10; i++)
{
    Console.Writeline(i);
}

This makes it clear what's going on, but it's not valid C#.

The best I've come up with so far is

int i;
for (int z; i<10; i++)
{
    Console.Writeline(i);
}

But that's ugly. Does C# give me an elegant way of doing it?

like image 832
James James Avatar asked Apr 30 '26 09:04

James James


2 Answers

Well, you don't have to have anything inside the first part of the loop:

for (; i < 10; i++)
{
    Console.WriteLine(i);
}

Is that what you're looking for? Personally I would typically try to avoid this sort of situation anyway though - I find it pretty unusual to want a loop without a new variable.

like image 127
Jon Skeet Avatar answered May 02 '26 21:05

Jon Skeet


Just use an empty first part of the "for":

int i;
for (; i<10; i++)
{
    Console.Writeline(i);
}
like image 24
Roee Gavirel Avatar answered May 02 '26 23:05

Roee Gavirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!