开发者

C#: Definition of the scope of variables declared in the initialization part of for-loops? [duplicate]

This question already has answers here: Closed 11 years ago.

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


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.


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.


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#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜