Question

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 ;)

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top