I’m just couris about whats happning behind the scenes. I have this code and of course it will not compile cause I create the hello variable inside a if statement and later try to declare it agian. Why dosen’t .NET allow me to do so? Whats happning behind the scences that could make the hello variable interfeer with the one inside the statement.
It’s very stright forward why this could interfeer if the variable was declared before the if statement.
public void Test() {
if (true)
{
var hello = "";
}
var hello = "";
Console.Write(hello);
}
Just to clarify, there are two rules violated here.
The first is that nested local variable declaration spaces may not contain two declarations of the same name.
The second is that nested local scopes may not contain two usages of the same simple name or declaration to mean two different things.
Both rules are violated. Note that the first rule is essentially a special case of the second rule. The second rule is more general; for example, this is also a violation:
Here the simple name
xis used to meanthis.xin one local scope and the local variablexin a nested scope. This is confusing; a simple name is required to mean the same thing throughout its entire block. We therefore make it illegal. This would be legal:Even though the local variable is declared in a scope nested inside the scope of the field, this is allowed because the field’s scope is not a local variable declaration space.
This is also legal:
because now the two conflicting usages of
xare both used consistently throughout the entirity of their immediately containing scopes. Those scopes now do not overlap, so this is allowed. (It is still a bad idea however.)These rules are there for your safety but they can be quite confusing. See
http://blogs.msdn.com/b/ericlippert/archive/tags/declaration+spaces/
and
http://blogs.msdn.com/b/ericlippert/archive/tags/scope/
for some articles on these language features.