-1

So I was doing a simple for loop and suddenly i got an scope error. if I change the i in int i = 100 it dissapears but I just want to understand why this happens.

The error appears int the for(int i = 0; i<10; i++)

A local parameter called 'i' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

class Class1
{
    static void Hi()
    {
        for(int i = 0; i<10; i++)
        {
            //do something
        }
        int i = 100;
    }
}
Gharsnull
  • 1
  • 2
  • All you have to do is use a different name for the variable, assuming that is not meant to be the same one. – insane_developer Aug 01 '20 at 17:55
  • The `for` variable is not defined inside of the loop scope. If it were then you would not see the increment changes each time the loop starts again. Basically a `for(a;b;c) { stuff; }` is just a `a; while(b) { stuff; c; }` – juharr Aug 01 '20 at 17:58
  • But this does work in Java, what is different in c# that makes this fail – Gharsnull Aug 01 '20 at 18:02
  • @gharsnull: It's a different language. I believe both standard C and C++ have the same behavior as C# (in the run-up to standardization, the rules changed). In C#, the `foreach` variable is local to the scope of the loop (this was a late, and breaking, change when lambdas were introduced). If you remove the declaration of `i`, changing your code to `i=100;`, it should work. – Flydog57 Aug 01 '20 at 19:11

1 Answers1

0

The declaration of int i = 100; is considered to be enclosing the for loop (regardless of whether it's not at the top of the method), so you cannot use the same name variable as one that appears in a block that contains your block.