The following code fails to compile stating "A local variable named 'st' cannot be declared in this scope because it would give a different meaning to 'st', which is already used in a 'child' scope to denote something else":
var l = new List<string>();
l.Find(st => st.EndsWith("12"));
string st = "why this fails?";
I understand why this won't 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?";
What I don't get is why is the compiler smart enough to see that postParent is not within scope, but won't let me define a new variable that has the same name as a variable used within a child scope (which is obviously out of scope at this point).
Is the compiler simple enforcing scope by refusing to let me use the variable? If so this makes sense.
===========
Edited:
I guess what I also find interesting is how you can have the same variable within two child scopes in a single method, so this is valid:
{
string thisWorks= string.Empty;
}
{
string thisWorks= "Should this work?";
}
I'm just a little curious that you can have two variables with the same name as long as they are at the same level (if you look at scope as 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 allow this, while it wouldn't allow the postParent variable. And is this a technical limitation or was this a design decision? That's what I'm really trying to get at;-)