I have been using C# for quite a long time but never realised the following:
public static void Main()
{
for (int i = 0; i < 5; i++)
{
}
int i = 4; //cannot declare as 'i' is declared in child scope
int A = i; //cannot assign as 'i' does not exist in this context
}
So why can I not use the value of 'i' outside of the for block if it does not allow me to declare a variable with this name?
I thought that the iterator variable used by a for-loop is valid only in its scope.
Look at it in the same way as if you could declare an
int
in ausing
block:However, since
int
does not implementIDisposable
, this can not be done. It may help someone visualize how anint
variable is placed in a private scope, though.Another way would be to say,
Hope this helps to visualize what is going on.
I really like this feature, as declaring the
int
from inside thefor
loop keeps the code nice and tight.If you'd declared
i
before yourfor
loop, do you think it should still be valid to declare it inside the loop?No, because then the scope of the two would overlap.
As for not being able to do
int A=i;
, well that's simply becausei
only exists in thefor
loop, like it should do.Also C#'s rules are many time not necessary in terms of programing strictly, but are there to keep your code clean and readable.
for example, they could have made it so that if you define it after the loop then it is ok, however it someone who reads your code and missed the definition line may think it has to do with the loop's variable.