In for loop case I can declare the index outside the for statement. For example, instead of
for (int i = 0; i < 8; i++) { }
I can do:
int i;
for (i = 0; i < 8; i++) { }
Now in compare to foreach loop, I have to declare the variable inside the loop:
foreach (string name in names) { }
And I cannot do something like:
string name;
foreach (name in names) { }
The reason this bothers me is that after the loop I want to use the variable “name” again. In case of foreach loop the variable “name” can’t be used since it outside of the foreach scope, and I cannot declare another variable with the same name since it declared before in the same scope.
Any idea?
Well, you can do:
Or more likely:
If the contents of the foreach loop is just to find a matching element – which at least sounds likely – then you should consider whether LINQ would be a better match:
Using LINQ can often make code which is basically trying to find something a lot simpler to read.