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?
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.
Just use an empty first part of the "for":
int i;
for (; i<10; i++)
{
Console.Writeline(i);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With