I am reading some C# text regarding scope of variables and got some confusion:
Case 1:
class A
{
void F() {
i = 1;
}
int i = 0;
}
Case 2
class A
{
void F()
{
i = 1; // Error, use precedes declaration
int i = 0;
}
}
in both case 1 and 2, the variable i is used before it is declared and initialized but why the Case 2 got error? (I have read an explanation that because i is a global variable in case 1, but still want to know if there is another explanation)
int iis a class variable in Case 1. When the class is defined, all the variables defined in the scope of theclass, not eachmethod, are also defined.In Case 2, you define the variable as part of the
method, and AFTER you use it.