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:
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":
You can also assign the variable to itself in the first part of the loop like this:
I find that it's slightly clearer than leaving the first part of the loop blank, however Visual Studio will give you a warning "Assignment made to the same variable; did you mean to assign it to something else?"