Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

I have 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 am compiling the above code I am getting following error

A local variable named 'n' cannot be declared in this scope

like image 677
santosh singh Avatar asked May 27 '11 17:05

santosh singh


1 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: which n are we talking about? If we're talking about the outer n, then n % 2 == 0 is always true since n is just 1000 (and therefore evens will comprise all numbers from 1 to 1000). On the other hand, if we're talking about the inner n, then n % 2 == 0 will only hold true for even values of n (and evens will be 2, 4, 6, ... 1000).

The important point to realize is that variables declared outside the lambda are accessible from within the lambda's scope.

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

This is why the ambiguity exists, and why it is therefore not allowed.


The solution is simply to pick a different variable name for your lambda; e.g.:

var ngt5 = numbers.Where(x => x > 5);
like image 75
Dan Tao Avatar answered Sep 28 '22 09:09

Dan Tao