views:

469

answers:

3

How can I (if it is possible at all) intialize multiple variables of different type in C# for cycle? Example:

for (MyClass i = 0, int j = 1;j<3;j++,i++)
+6  A: 

It can't be done. Put one of the declarations before the loop:

MyClass i = 0;
for (int j = 1; j < 3; j++, i++)

Or for symmetry, both of them:

MyClass i = 0;
int j = 1;
for (; j < 3; j++, i++)

It's also possible that one of the variables is more primary than the other. In that case it might be neater to have one be the loop variable, and deal with the other seperately, like this:

MyClass i = 0;
for (int j = 0; j < 3; j++)
{
    ...
    i++;
}

Note that if i and j were of the same type, then you could declare them both in the for-loop:

for (int i = 0, j = 1; j < 3; j++, i++)
Joren
A: 

I don't think you can define more than one type inside a for loop. only for(int i=0,j=3; j<7; j++, i++)

Dani
A: 

You can initialize different types inside a for statement, but you cannot declare different types in a for statement. In order to initialize different types inside a for statement you must declare all the types before the for loop. For example:

int xx;
string yy;
for(xx=0, yy=""; xx<10; xx++)
    {
    ....
    }
Bill W