Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, the compiler is enforcing scope. Note that the scope of a variable is the lexical block it's part of - not just from the point of declaration onwards, but the whole scope. </p> <p>The compiler is complaining because the assignment to <code>postParent</code> is outside its scope (which is only the nested braces). If you tried to declare a new variable at the point where you're currently assigning to <code>postParent</code> the problem would be with the nested block, because the scope of <code>postParent</code> would include that nested block, even though it was before the declaration.</p> <p>Scopes are described in section 3.7 of the C# 3.0 specification.</p> <p>EDIT: To respond to your question edit.</p> <p>It's just two simple rules:</p> <ul> <li>you can't declare a local variable when another local variable with the same name is in scope</li> <li>the scope of a local variable is the block in which the declaration occurs</li> </ul> <p>I'm sure the language could have been designed such that the scope only began at the point of declaration, but I think it's simpler (in terms of language complexity) to consider scopes as just blocks - so all local variables declared in the same block have the same scope, for example. That makes life a lot simpler when considering captured variables, too - as what gets captured depends on the scope, and nested scopes make life interesting...</p> <p>EDIT: The language spec has this to say about the original lambda expression example - it's section 7.14.1:</p> <blockquote> <p>The optional anonymous-function-signature of an anonymous function defines the names and optionally the types of the formal parameters for the anonymous function. The scope of the parameters of the anonymous function is the anonymous-function-body. Together with the parameter list (if given), the anonymous-method-body constitutes a declaration space. For this reason, it is a compile-time error for the name of a parameter of the anonymous function to match the name of a local variable, local constant, or parameter whose scope includes the anonymous-method-expression or lambda-expression.</p> </blockquote> <p>Does that help?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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