The following code cannot compile: "A local variable with the name" st "cannot be declared in this scope because it would give the value" st ", which is already used in the scope of" child "to mean something else" :
var l = new List<string>(); l.Find(st => st.EndsWith("12")); string st = "why this fails?";
I understand why this will not work:
string preParent = ""; { string preParent = "Should fail cause we change the meaning"; }
When we do the following, we get "CS0103: the name" postParent "does not exist in the current context":
{ string postParent=string.Empty; } postParent = "Should this work?";
I donβt understand why the compiler is smart enough to see that postParent is not in scope, but it will not allow me to define a new variable that has the same name as the variable used within the child scope (which is obviously out of scope of this paragraph).
Is the compiler a simple scope, refusing to let me use a variable? If so, that makes sense.
============
Edited by:
I think the interesting thing is how you can have the same variable in two child areas in the same method, so this is valid:
{ string thisWorks= string.Empty; } { string thisWorks= "Should this work?"; }
I'm just curious that you can have two variables with the same name if they are on the same level (if you look at the area like a tree). This makes sense because you can have local variables in two methods of the same class with the same name.
I'm just surprised that the compiler is able to differentiate and resolve this, while it will not allow the postParent variable. And is it a technical limitation or is it a design decision? This is what I'm really trying to get to -)
scope compiler-construction c #
JoshBerke Nov 17 '08 at 20:18 2008-11-17 20:18
source share