0

I'm confused why is there compiler error CS0136 "A local or parameter named 'a' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter" in loops of that kind? Isn't first a enclosed inside the loop?

     static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            int a = 0;
        }

        int a = 1;
    }

If not, why is there compiler Error CS0841 Cannot use local variable 'b' before it is declared in this variant

static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            int a = b;
        }

        int b = 1;
    }

Is there any contradiction here and why is this restriction made for?

Dork
  • 1,816
  • 9
  • 29
  • 57

1 Answers1

0

In your first function, the function itself is a variable scope. As Sinatr mentioned, you can declare an enclosing scope, but this scope cannot contradict the general function's scope. As mentioned by John Skeet (Why can't a duplicate variable name be declared in a nested local scope?), your problem is that the compiler thinks that your attempt to declare a new a in a child scope is actually an illegal attempt to reference your parent a, which has not yet been declared.

In your second function, the difference is that you are attempting to address the variable b before it is declared. You are calling

int a = b;

within a loop, and then only after the loop is ended do you call

int b = 1;
Community
  • 1
  • 1
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40