开发者

C#: Why is this variable in scope and out of scope at the same time? [duplicate]

This question already has answers here: Closed 11 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜