mercredi 4 mars 2015

Why does declaring a variable of the same name as in for loop causes variable name ambiguity in C# in opposition to Java [duplicate]




This question already has an answer here:




As for Java refugee this code is perfectly fine. The int i lives in the loop only and the second int i causes no conflict. So there should be no problem. Altough, This code in C# causes i variable ambiguity.



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


Thus(beign naive) this code should be valid



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


but it says the i variable is not declared which as expected is true. Finally only nesting second int i in the block fixes the ambiguity:



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


The question is: what rule/mechanism of C# language causes variable name ambiguity in the first example given?


The printscreen from VS2013:


enter image description here




Aucun commentaire:

Enregistrer un commentaire