Note that there are some explanatory texts on larger screens.

plurals
  1. POLambda Scope Clarification
    text
    copied!<p>Why does my parameter <code>x</code> behave so erratically?</p> <ol> <li>Example 1 - Doesn't exist in the current context.</li> <li>Example 2 - Cannot reuse <code>x</code> because it's defined in a 'child' scope.</li> <li>Example 3 - Fine. This is the part where I am confused. Perhaps a different 'child' scope?</li> </ol> <p><strong>Example 1</strong>:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 3, 4, 5 }; var result = list.Where(x =&gt; x &lt; 3); Console.Write(result.ElementAt(x)); </code></pre> <p>creates this compile time error:</p> <blockquote> <p>The name 'x' does not exist in the current context</p> </blockquote> <p>which I expect.</p> <p><strong>Example 2</strong>:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 3, 4, 5 }; var result = list.Where(x =&gt; x &lt; 3); int x = 1; Console.Write(result.ElementAt(x)); </code></pre> <p>produces this compile-time error:</p> <blockquote> <p>A local variable named '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</p> </blockquote> <p>I understand the scoping as answered in this question, <a href="https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach">Is there a reason for C#&#39;s reuse of the variable in a foreach?</a>. However, this is something I've never seen before. In addition, it makes the answers to this question, <a href="https://stackoverflow.com/questions/10494074/what-is-the-scope-of-a-lambda-variable-in-c">What is the scope of a lambda variable in C#?</a>, incomplete or wrong.</p> <p><strong>Example 3</strong>:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 3, 4, 5 }; List&lt;string&gt; stringList = new List&lt;string&gt; { "A", "B" }; var result = list.Where(x =&gt; x &lt; 3); var result2 = stringList.Where(x =&gt; x != "A"); Console.Write(result2); </code></pre> <p>No errors produced.</p> <p><hr /> With the accepted answer, these blog posts from Eric Lippert helped me wrap my head around what was happening. If anyone is still confused:</p> <p><a href="http://blogs.msdn.com/b/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx" rel="nofollow noreferrer"><strong>declaration space</strong></a></p> <p><a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx" rel="nofollow noreferrer"><strong>simple names</strong></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload