Reputation: 24063
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?
Upvotes: 15
Views: 11369
Reputation: 1500535
Well, you can do:
string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
name = loopName;
// other stuff
}
Or more likely:
string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
if (someCondition.IsTrueFor(loopName)
{
name = loopName;
break;
}
}
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:
string name = names.Where(x => x.StartsWith("Fred"))
.FirstOrDefault();
Using LINQ can often make code which is basically trying to find something a lot simpler to read.
Upvotes: 16
Reputation: 11090
You can't do this in foreach loops. You are creating and using a range variable whose scope is limited to the foreach query.
If you need to use an individual name from within the names collection then you can assign it to a value outside of the foreach loop:
foreach(string name in names)
{
if(name == someCondition)
someVariable = name;
}
Upvotes: 1