Why Lambda variable scope exists outside LINQ Query?
.net, c#, linq, scope
Solution
It's not about LINQ it's about child scopes.
For example:
foreach (var bar in FooBar.Bars)
{
var x = FooBar.GetFoo();
}
var x = new Foo();
produces exactly the same error message from compiler.
To fix that you just have to place variables in different (non-nesting) scopes. For example:
foreach (var bar in FooBar.Bars)
{
var x = FooBar.GetBar();
}
{
var x = new Foo();
}
Problem
I read this question(What is the scope of a lambda variable in C#?) But it is about Lambda variable scope inside LINQ Query. Now to my question Lets say I have a very simple LINQ query. ``` var Foo = FoobBar.Select(x => x); var x = somefunction(); ``` Compiler says : `A local variable 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'child' scope to denote something else`. Why is that so? Shouldn't Lambda variable cease to exist when LINQ query ends? EDIT: After reading answers i came to conclusion that its the outside `x` (returned from function) whose scope extends inside LINQ Query.