Sign in to follow this  
Alpha_ProgDes

foreach variable not local?

Recommended Posts

Alpha_ProgDes    6921
confused about the following:
int item = 0;
int[] list = new int[10];

for (int i = 0; i < list.Length; ++i)
{
   list[i] = ++item;
}

foreach (int item in list)  // problem here
{
   System.Console.WriteLine(item);
}
Now why is the compiler complaining that item is being redeclared? Isn't the item in the foreach loop local to only the loop? And therefore hides the item declared above it?

Share this post


Link to post
Share on other sites
dillscon    142
You already declared int item before your for loop.

Do this...


int item = 0; //see item is already delcared here
int[] list = new int[10];

for (int i = 0; i < list.Length; ++i)
{
list[i] = ++item;
}

foreach (int j in list) // I'm sure theres a better name than j for you to use
{
System.Console.WriteLine(j);
}



Share this post


Link to post
Share on other sites
cshowe    360
This post by Raymond Chen

http://blogs.msdn.com/oldnewthing/archive/2007/08/14/4374222.aspx

And this by Eric Lippert

http://blogs.msdn.com/ericlippert/archive/2007/08/14/c-and-the-pit-of-despair.aspx


Don't address you case specifically but suggest that it is to avoid subtle shadowing bugs.

Share this post


Link to post
Share on other sites
dillscon    142
Quote:
Original post by Alpha_ProgDes
So I can't do this either?
*** Source Snippet Removed ***
That sucks...


No but you can do this...



int item = 0;

//...code...
while (var < 10393)
{
item = 15;
//...code....
}




You can use the variable through out whatever method you're working on you just cant redeclare it. But I think in the case of the foreach loop you do have to delare the variable you use in the loop.




Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this