4

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?

Community
  • 1
  • 1
Bob
  • 7,851
  • 5
  • 36
  • 48
  • I've noticed this before and wondered about it. Personally I'm surprised the first doesn't compile, while it seems right that the second one should not compile. – Rob Levine Mar 31 '11 at 16:46

2 Answers2

5

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79