Multiple initialization in C# 'for' loop

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++)

Of course it CAN be done. Just use the dynamic keyword:

public static void Main(string[] args) {
    for (dynamic x = 0, y = new MyClass { a = 20, b = 30 }; x < 100; x++, y.a++, y.b--) {
        Console.Write("X=" + x + " (" + x.GetType() + "\n" +
                      "Y.a=" + y.a + ",Y.b=" + y.b + " (" + y.GetType() + "\n");
     }
}

class MyClass {
    public int a = 0, b = 0;
}

Have a great day!


Yes, it can be done. You can initialize variables of different types inside a for statement, but you cannot declare variables of different types inside a for statement. In order to initialize variables of 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++)
    {
    ....
    }

[EDIT] Adding more information for completeness. This goes beyond what the OP requested, but may be helpful for others. It is simple to initialize variables of the same type in a for loop, just separate the initialization by commas. You can also have multiple variables changed in the third section. You cannot have multiple comma separated sections in the second, comparison section, but you can use && || and ! to make a complex Boolean section based on multiple variables.

for(int i=0, j=0, k=99; i<10 && k<200; i++, j++, k += 2)

However, it is not a good practice to make a for statement that is so complex that it is difficult to understand what is going on.