Variable declared in for-loop is local variable?

2019-03-08 09:21发布

I have been using C# for quite a long time but never realised the following:

 public static void Main()
 {
     for (int i = 0; i < 5; i++)
     {

     }

     int i = 4;  //cannot declare as 'i' is declared in child scope                
     int A = i;  //cannot assign as 'i' does not exist in this context
 }

So why can I not use the value of 'i' outside of the for block if it does not allow me to declare a variable with this name?

I thought that the iterator variable used by a for-loop is valid only in its scope.

9条回答
疯言疯语
2楼-- · 2019-03-08 09:47

Look at it in the same way as if you could declare an int in a using block:

using (int i = 0) {
  // i is in scope here
}
// here, i is out of scope

However, since int does not implement IDisposable, this can not be done. It may help someone visualize how an int variable is placed in a private scope, though.

Another way would be to say,

if (true) {
  int i = 0;
  // i is in scope here
}
// here, i is out of scope

Hope this helps to visualize what is going on.

I really like this feature, as declaring the int from inside the for loop keeps the code nice and tight.

查看更多
闹够了就滚
3楼-- · 2019-03-08 09:52

If you'd declared i before your for loop, do you think it should still be valid to declare it inside the loop?

No, because then the scope of the two would overlap.

As for not being able to do int A=i;, well that's simply because i only exists in the for loop, like it should do.

查看更多
ら.Afraid
4楼-- · 2019-03-08 09:53

Also C#'s rules are many time not necessary in terms of programing strictly, but are there to keep your code clean and readable.

for example, they could have made it so that if you define it after the loop then it is ok, however it someone who reads your code and missed the definition line may think it has to do with the loop's variable.

查看更多
登录 后发表回答