What is the scope of local variable declared in Linq Query.
I was writing following code
static void Evaluate()
{
var listNumbers = Enumerable.Range(1, 10).Select(i => i);
int i = 10;
}
Compiler flagged error on line int i=10, stating
A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else
I am unable to understand why this error is coming.
My understanding was that i
will become out of scope after first line (in foreach loop). So i
can be declared again.
Actual behavior is that i
cannot be accessed after first line (in foreach loop), which is correct. But i
cannot be declared again. This seems strange.
EDIT This is a following question based on response by Andras. The answer is very good, but causes further doubts.
static void Evaluate3()
{
var listNumbers = Enumerable.Range(1, 10).Select(i => i);
var listNumbers1 = Enumerable.Range(1, 10).Select(i => i);
}
Based on the logic of function Evaluate that .Select(i=>i), and int i=10, both i, are local to function block and hence complication error.
Function Evaluate3 should not compile as well as there are two i in the method block, but it is compiling successfully without any warning/error.
Question, Either both Evaluate and Evaluate3 should not compile, or both should compile.