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()
{
There is no naming conflict. The compiler always takes the nearest
/least scope variable.
In this case, thats the x variable you declare in foo
.
Every variable can be accessed in a specific way, so theres no naming conflict.
If you want to access the outer x you can use this.x
.
The C# 4.0 spec says this about scope hiding through nesting:
3.7.1.1 Hiding through nesting
Name hiding through nesting can occur as a result of nesting namespaces or types within namespaces, as a result of nesting types within classes or structs, and as a result of parameter and local variable declarations. In the example
class A {
int i = 0;
void F() {
int i = 1;
}
void G() {
i = 1;
}
}
within the F method, the instance variable i is hidden by the local variable i, but within the G method, i still refers to the instance variable.
When a name in an inner scope hides a name in an outer scope, it hides all overloaded occurrences of that name.
In the example
class Outer {
static void F(int i) {}
static void F(string s) {}
class Inner
{
void G() {
F(1); // Invokes Outer.Inner.F
F("Hello"); // Error
}
static void F(long l) {}
}
}
the call F(1) invokes the F declared in Inner because all outer occurrences of F are hidden by the inner declaration. For the same reason, the call F("Hello") results in a compile-time error.
Because the rule is that if a conflict exists between a local variable and a class member, the local variable has higher precedence.
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.
This is not a naming conflict: in C#, local variables take precedence over instance variables with the same name, because their scope is narrower.
When the compiler matches a name reference to a name declaration, it uses the matching declaration with the narrowest scope
See documentation on Reference Matching for detailed information on the subject.
This is not ambiguous the local will be the variable that is assumed to reffed to in your function. If you need to get the class variable this.x allows the name resolution.