C#: Why is this variable in scope and out of scope at the same time? [duplicate]
Possible Duplicate:
C# Variable Scoping
I've run into something I've never encountered before. I'm not looking for a fix as I know how to solve it. What I'd like to know is what the compiler 开发者_开发技巧is doing. This is just example code:
if (true)
{
int x = 0;
}
int x = 0;
That code produces the error "A local variable 'x' cannot be declared in this scope because it would give a different meaning to 'x'".
However, it I change the code to this:
if (true)
{
int x = 0;
}
x = 0;
I get the error "Cannot resolve symbol 'x'".
So, what's going on here? How is it that x is both in scope and out of scope?
A variable's scope is the entire block in which it is declared. However, you can't refer to it until after the declaration.
Eric Lippert has a blog post on this which goes into more detail. EDIT: And as Eric points out, another one...
Its not, simply because C# allows you to declare/define variables anywhere in the program its scope is the entire block in which it is declared ans so it is making the x
predeclared/(in scope) for x
in if
block
精彩评论