5

I have following code

using(some code)
{
var b = .... 
}
var b = ...

Erorr: A local variable named 'b' cannot be declared in this scope because it would give a different meaning to 'b', which is already used in a 'child' scope to denote something else

Ok, editing

using(some code)
{
var b = .... 
}
b = ...

Error: The name 'b' does not exist in the current context

isxaker
  • 8,446
  • 12
  • 60
  • 87
  • 2
    +1: The first compiler error always puzzled me. – Daniel Hilgarth Aug 09 '13 at 06:40
  • 4
    This looks related to the following post on SO: http://stackoverflow.com/questions/6156449/why-cant-a-duplicate-variable-name-be-declared-in-a-nested-local-scope – DarkKnight Aug 09 '13 at 06:41
  • http://stackoverflow.com/questions/4649947/why-doesnt-c-sharp-allow-me-to-use-the-same-variable-name-in-different-scopes – Karthik Aug 09 '13 at 06:42
  • 4
    The c# standard claims that the scope of a variable includes the entire block in which it is declared, even that part of the block *before* the actual declaration. Weird, but true. So the scope of the second `var b` in the example actually extends to *before* the `using`. The question is: Why does the standard define the scope like that? I *think* the answer is: To avoid confusion and allow more reordering of lines without changing the semantics. – Matthew Watson Aug 09 '13 at 06:44
  • 1
    @MatthewWatson this is almost an answer :) – Matten Aug 09 '13 at 06:48
  • 1
    I might guess.. that using statement must be part of some function. Now for the scope of that function all variable should be unique. Additionally it is limiting variable scope to particular { } block. Meaning. It must be try to avoid duplicate reference by giving using{ } functionality. – Sumit Kapadia Aug 09 '13 at 06:56

3 Answers3

8

"The local variable declaration space of a block includes any nested blocks. Thus, within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block." Variable Scopes, MSDN

Xin
  • 1,300
  • 2
  • 14
  • 27
1

can you do this?

for (int i = 0; i < 10; i++)
{
    int j = 1;
}
 int j = 2;

The answer is NO which means it pretty much consistent everywhere. Now it begs the question why. Answer to this question is It is illegal to have two local variables of the same name in the same local variable declaration space or nested local variable declaration spaces. And in the above case declaration of J is within the same nested scope.

Ehsan
  • 31,833
  • 6
  • 56
  • 65
  • Yeah... scoped variables cascade. You can access a scoped variable from any child scope of the variables scope... That's a lot of "scope"... – gislikonrad Aug 09 '13 at 10:14
-2

The correct code should be:

var b = something;
using(some code)
{
    b = smth;
}
b = smth;

You cannot use a variable declared inside a block ({}) outside of that block.

Huy Do
  • 44
  • 6