Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable name used in a child scope [duplicate]

Tags:

c#

I've been wondering why in C# using a variable name used previously in a child scope is not allowed. Like this:

if (true)
{
    int i = 1;
}

int i = 2;

Compiling the above code produces an error:

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

And yet you can't use the variable defined in child scope either. The code above works just fine in Java and I can see no reason why it doesn't in C# too. I'm sure there's a good reason, but what is it?

like image 776
Carlos Avatar asked Jan 13 '10 18:01

Carlos


People also ask

Can the same variable name be declared in different scopes?

Do not use the same variable name in two scopes where one scope is contained in another. For example, No other variable should share the name of a global variable if the other variable is in a subscope of the global variable.

Is it legal to define a local variable with same identifier in the nested block?

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. Essentially, it's not allowed because, in C#, their scopes actually do overlap.

What is variable scope C#?

C# Class Level Variable Scope In C#, when we declare a variable inside a class, the variable can be accessed within the class. This is known as class level variable scope. Class level variables are known as fields and they are declared outside of methods, constructors, and blocks of the class.


2 Answers

It is a design choice made by the designers of C#. It reduces potential ambiguity.

You can use it in one of the two places, inside the if or outside, but you can only define it in one place. Otherwise, you get a compiler error, as you found.

like image 72
Adam Crossland Avatar answered Oct 05 '22 13:10

Adam Crossland


Something I noticed that was not noted here. This will compile:

for (int i = 0; i < 10; i++)
{
    int a = i * 2;
}
for (int i = 0; i < 5; i++)
{
    int b = i * 2;
}

Taken together, these design decisions seem inconsistent, or at least oddly restrictive and permissive, respectively.

like image 40
jeffmk Avatar answered Oct 05 '22 13:10

jeffmk