3

Possible Duplicate:
Why can't a duplicate variable name be declared in a nested local scope?

Hy guys, today I found an issue, on which i am not sure:

I thought the following example should be correct, because the braces create a new local area, so i can't access the first x after the braces and i should be able to create a new variable with the same name, after the closing brace.

 {
     int x = 0;
 }
 int x;

But if i try this example, i get the error: "A local variable name "x" cannot be declared in this scope because it would give a different meaning to "temp", which is already used in a parent or current scope to denote something else."

Is this really not allowed in C#? It could also be a fault of ReSharper 7.0, or of the Visual Studio 2012.

Please do not come up with bad coding style, this is just about my basic understanding of c#.

Thank You and a nice day ;)

Community
  • 1
  • 1
Iqon
  • 1,920
  • 12
  • 20

1 Answers1

4

The problem is that primacy doesn't matter. You wouldn't have expected this to work:

int x;
{
  int x = 0;
}

Why not? Because the scope of the first variable extends into the curly brackets. Even though the scope of the second variable doesn't extend outside of those brackets, declaring the second variable causes a problem.

The same principle applies if you reverse the order.The first variable doesn't prevent you from declaring the second, but the second variable prevents you from declaring the first.

If you create the second variable in its own scope, it will behave the way you expect.

{
  int x = 0;
}
{
  int x;
}
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • So you're saying it doesn't matter *where* you actually define a variable in a block of code? – Mike Christensen Sep 18 '12 at 22:45
  • From a scope point of view that is.. Obviously you wouldn't be able to *refer* to a variable before the line it was declared on (that would be weird).. – Mike Christensen Sep 18 '12 at 22:50
  • @MikeChristensen: Precisely. When a variable is declared, even though you can't *use* that variable above the point in code where it's declared, its name belongs to the entire scope. So if you declare a conflicting variable in the same scope or a sub-scope, the compiler will complain. – StriplingWarrior Sep 18 '12 at 23:00