A local variable cannot be declared in this scope [Linq / Lambda expression]

I have the following code snippet in C #

static void Main() { var numbers = new[] { 1, 2, 3, 4, 5, 6 }; var ngt5 = numbers.Where(n => n > 5); var n = ngt5.First().ToString(); Console.WriteLine(n, numbers); } 

When I compile the above code, I get the following error

A local variable named "n" cannot be declared in this scope.

+6
c # linq
May 27 '11 at 17:29
source share
2 answers

Your problem is here:

 // Within your lambda you have an 'n'. var ngt5 = numbers.Where(n => n > 5); // And within the outer scope you also have an 'n'. var n = ngt5.First().ToString(); 



To understand why this is a problem, consider the following code:

 int n = 1000; var evens = Enumerable.Range(1, 1000).Where(n => n % 2 == 0); 

The expression n % 2 == 0 above is ambiguous: what are we talking about n ? If we are talking about external n , then n % 2 == 0 always matters, since n is only 1000 (and therefore evens will contain all numbers from 1 to 1000). On the other hand, if we are talking about internal n , then n % 2 == 0 will be true only for even values โ€‹โ€‹of n (and evens will be 2, 4, 6, ... 1000).

An important point to implement is that variables declared outside of lambda are accessible from the lambda area.

 int n = 0; Action incrementN = () => n++; // accessing an outer variable incrementN(); Console.WriteLine(n); // outputs '1' 

That is why there is ambiguity and why it is not allowed.




The solution is simply to choose a different variable name for your lambda; eg:.

 var ngt5 = numbers.Where(x => x > 5); 
+17
May 27 '11 at 17:31
source share

Your problem is that you assume that closures are first-class functions in C #, which is not the case, and I would like that to be the case.

You cannot consider C # scope as an isolated scope of functions.

You cannot return a complex Linq expression outside the current scope.

JavaScript allows this ambiguity, which allows you to write closures without restrictions, which makes the closure of functions of the first class JavaScript.

0
Feb 27 '13 at 18:50
source share



All Articles