C# variable scoping not consistent?

2019-04-08 13:41发布

C# is quite nit-picking when it comes to variable scoping. How is it possible that it accepts this code:

class Program
{
    int x = 0;

    void foo()
    {
        int x = 0;
        x = 1;

        Console.WriteLine(x);
    }
}

If you ask me, that's an obvious naming conflict. Still the compiler (VS 2010) accepts it. Why?

标签: c# scope
7条回答
女痞
2楼-- · 2019-04-08 14:13

Thats normal.

In constructors I often use the same.

public Person(string name) {
  this.name = name;
}

Else it would be not possible to declare method parameters which are named like member variables.

查看更多
登录 后发表回答