I get the error :
A local variable named ‘s’ cannot be
declared in this scope because it
would give a different meaning to ‘s’,
which is already used in a ‘child’
scope to denote something else.
static void Main(string[] args)
{
string s = "hello"; // Line 1
var test = new[] { "abd", "def" }.Select(s => s.StartsWith("a")); // Line 2
}
Why?
I would have guessed that the ‘s’ from line 1 would be shaded by the ‘.Select(s =>..’ decleration in line 2 but – as far as I can tell – this is not the case..
PS I’m not sure that shaded it the proper term – please correct me if a better word/phrase exsists.
You get an error for the same reason that in a normal code block (like an if statement or loop), you cannot declare variables with the same name as outside the code block.
This is different than for class variables and method variables, where you can explicitly reference class variables with the this keyword.
I think that the this keyword is the key, as there isn’t any way of explicitly referencing variables that are in the same method but in different code blocks.