A Quick Lesson on For Loops in C#

For the longest time, I thought I knew everything there was to know about for loops in C#. Hubris, I know. But, today, I wanted to construct a complex loop in which I needed to keep track of two simultaneous values; namely, an int counter and a current object. I would have bet money that I could write something like this:

for (int count = 0, object x = GetSomeObj(); /* condition */; ++count, x = GetNextObj(x))
{
    ...
}

But alas, the compiler complained.

error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement

I solved this problem by declaring my variables just above the loop:

int count;
object x;
for (count = 0, x = GetSomeObj(); /* condition */; ++count, x = GetNextObj(x))
{
    ...
}

It turns out that the compiler is fine with the same type, such as when you declare:

int i = 0, j = 1, k = 2;

However, when mixing types, you’re out of luck.

For more information on the subject, see: http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/93dfb7ee-23f7-47d5-8ff9-af7bc5759933


Leave a comment