Soatl
Soatl

Reputation: 10592

Behavior with Class and Method Variables with the same names

Earlier I had an issue where I discovered some weird behavior with C#.

This will throw an error:

 public class MyClass
 {
    public int MyMethod()
    {
        for(int x = 0; x < 1; x++)
        {
           for(int x = 0; x < 1; x++)
           {
           }
        }
    }
 }

But this will not:

public class MyClass
{
    public int x = 0;
    public int MyMethod()
    {
        for(int x = 0; x < 1; x++)
        {
        }
    }
}

Instead, when for loop ends, x will be set back to 0. This will also work if you have one int x and one bool x.

Why does this work?

Upvotes: 2

Views: 92

Answers (1)

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

In the first case you are defining the same variable within the same scope, twice, which is an error.

In the second case, you are defining a local variable within the scope of the loop, which will hide the class member x within that scope. Outside that scope, x will refer to the class member, but inside it will refer to the loop iteration variable.

Upvotes: 7

Related Questions