Область видимости локальной переменной C # [дубликат]
Possible Duplicate:
confused with the scope in c#
Похоже, что в C # переменная, определенная в локальной области видимости для блока if / else / loop, конфликтует с переменной, определенной за пределами этого блока - см. Фрагмент кода. Эквивалентный код прекрасно компилируется на C / C ++ и Java. Это ожидаемое поведение в C #?
public void f(){
if (true) {
/* local if scope */
int a = 1;
System.Console.WriteLine(a);
} else {
/* does not conflict with local from the same if/else */
int a = 2;
System.Console.WriteLine(a);
}
if (true) {
/* does not conflict with local from the different if */
int a = 3;
System.Console.WriteLine(a);
}
/* doing this:
* int a = 5;
* results in: Error 1 A local variable named 'a' cannot be declared in this scope
* because it would give a different meaning to 'a', which is already used in a
* 'child' scope to denote something else
* Which suggests (IMHO incorrectly) that variable 'a' is visible in this scope
*/
/* doing this:
* System.Console.WriteLine(a);
* results in: Error 1 The name 'a' does not exist in the current context..
* Which correctly indicates that variable 'a' is not visible in this scope
*/
}