Why does a Lambda variable scope exist outside of a LINQ query?

I read this question ( What is the scope of a lambda variable in C #? )

But this is about the scope of the Lambda variable inside the LINQ query.

Now to my question

Let's say I have a very simple LINQ query.

var Foo = FoobBar.Select(x => x);
var x = somefunction();

The 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 this so? Should a Lambda variable cease to exist when a LINQ query completes?

The EDIT: . After reading the answers, I came to the conclusion that its external x(returned by the function), the volume of which is distributed inside LINQ Query.

+5
source share
5 answers

This is not about LINQ about children.

For instance:

foreach (var bar in FooBar.Bars)
        {
            var x = FooBar.GetFoo();
        }
var x = new Foo();

prints exactly the same error message from the compiler.

, (-) . :

foreach (var bar in FooBar.Bars)
        {
            var x = FooBar.GetBar();
        }
{
    var x = new Foo();
}
+9

,

var Foo = FoobBar.Select(x => x);

true x

var x = somefunction()

, , lamda, , . "x", "child" ( )

, ,

{
var x = somefunction()
}
+4

, # , :

static void test() {

    Action<int> x = (z) => {
        Console.WriteLine(z);               
    };


    int[] i = { 5,2,0,1,3,1,4 };

    var kyrie = i.Select (x => x);

}

#, Action x kyrie; , , # ? # ?

# , , . http://www.anicehumble.com/2012/05/java-said-c-said-scope-consistency.html

, # ,

. #

+2

(), "x" "x" ( =>).

, :

var Foo = FoobBar.Select(y => x);
var x = somefunction();

x " ".

+1

.

" " ,

void method()
{
    int a;
    int a; //wrong!
}

, - .

void method()
{
    int a;
    for(;;)
    {
        int a; //wrong again!
    }
}

, int .

+1

All Articles