5

Possible Duplicates:
confused with the scope in c#
C# Variable Scoping

I am curious about the design considerations behind the scope of variables which are declared in the initialization part of for-loops (etc). Such variables neither seem to be in-scope or out-of scope or am I missing something? Why is this and when is this desired? Ie:

for (int i = 0; i < 10; i++)
{
}

i = 12;       //CS0103: The name 'i' does not exist in the current context

int i = 13;   //CS0136: A local variable named 'i' cannot be declared in this scope 
              //because it would give a different meaning to 'i', which is already 
              //used in a 'child' scope to denote something else
Community
  • 1
  • 1
Avada Kedavra
  • 8,523
  • 5
  • 32
  • 48

3 Answers3

3

The loop variable is scoped to the loop itself. This is why you see the expected result of i not being available outside the loop.

The fact you can't declare i outside the loop is a bit more puzzling but is to do with the fact that once compiled all the variable declarations can be considered to be at the beginning of the block they are declared in. That is your code in practice is the same as:

int i;

for (int i = 0; i < 10; i++)
{
}

i = 13; 

Hopefully it is obvious here that you have a name collision. As for why it works like that I can't tell you for sure. I'm not that up on what compilers do under the hood but hopefully somebody else will pop up and explain why.

Chris
  • 27,210
  • 6
  • 71
  • 92
  • Thanks for you answer Chris. The example above quite obviously results in a name collision. If that is how the compiles *sees* it then it is understandable. +1 and accepted. – Avada Kedavra Sep 29 '11 at 09:53
1

When you declare i=13 it has a scope of method. So in that method you already have declared variable i and second declaration in the scope of the for loop will be duplicate.

user880385
  • 98
  • 1
  • 5
  • Accept if it had a scope of Method then wouldn't you be able to reference it outside the scope of the for loop? Notice the line that sets i = 12. – giltanis Aug 05 '11 at 10:50
0

Design consideration was quite simple: to avoid confusion. There is little if any reason to allow hiding of outer variable name. It's not just cycles BTW, this rule applies to any inner/outer scopes in C#.

Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96