See below code snippets
class scopes
{
static int j=20;
Console.WriteLine(j);
public static void Main()
{
int j=30;
Console.WriteLine(j);
return;
}
}
For above code , variable hiding is supported
see below code
public static int Main()
{
int j = 20;
for (int i=0; i < 10; i++)
{
int j = 30; //can't do this
Console.WriteLine(j + i);
}
return 0;
}
Here for above code variable hiding is not supported.
What is the reason behind this?
In the first case, there is at least a defined way to disambiguate between the two things, i.e. the
this.prefix – inside the method,this.jis the field, where-asjis the member. As for why this is supported: speculation, but probably so that adding a field to the class (which could be in a different code file in the case ofpartialclasses) doesn’t cause random methods to start throwing compiler errors. Note that the meaning in ofjin the method is identical before and after the fieldjis added.In the second case, this is not a concern: adding locals can only impact the single local method, and there is no disambiguation syntax (i.e. which
jdo we mean), and no risk of accidental breakage from unrelated code.