Syntax error

W

web1110

In the following code I get an error. I delcare and use "MenuItem
mniBackItem" within the loop. After exiting the loop, I use it again. But
I get the following error on the declaration after the loop:

S:\Acorn\Applications\APPRunner\FRMRun\FRMRun.cs(231): A local variable
named 'mniBackItem' cannot be declared in this scope because it would give a
different meaning to 'mniBackItem', which is already used in a 'child' scope
to denote something else

I thought that after I left the loop, I could reuse then name like in C.
Changing the name works. So can I assume that in C#, a variable name
declared within a block (loop) cannot be used below that block?

===================================================

private void mniBack_Select(object sender, System.EventArgs e)
{
int siControlCnt=clControlManager.siControlDepth;
string[] astrControlNames = new String[siControlCnt];
clControlManager.siGetControlNames(ref astrControlNames);
mniBack.MenuItems.Clear();

for(int si=0; si<siControlCnt;si++)
{
if(astrControlNames[si]==String.Empty)
{
break;
}
MenuItem mniBackItem = new MenuItem();
mniBackItem.Click += new System.EventHandler(this.vdBackClick);
mniBackItem.Text = astrControlNames[si];
mniBack.MenuItems.Add(mniBackItem);
}

MenuItem mniBackItem = new MenuItem();
<-------------------------------- ERRORS BEGIN HERE
mniBackItem.Click += new System.EventHandler(this.vdBackClick);
mniBackItem.Text = astrControlNames[si];
mniBack.MenuItems.Add(mniBackItem);
}
 
D

DalePres

You can reuse it in another block at the same level as the original block
but using it at a higher level block gives it precedence over the inner
block. The order in which you declare it in code doesn't matter. Just use
a different name or put the second use in a block as well.

HTH

DalePres
MCAD, MCDBA, MCSE
 
B

Bruce Wood

No, you cannot reuse the name. The reason for this seems to have more
to do with style than with the compiler. (The compiler could quite
easily keep track of the two different variables in two different
scopes.) However, it's simply confusing for people reading the code:
there are two different, independent variables named mniBackItem, one
in a parent scope and the other in a child scope. I think that's why
the compiler complains.

You can, however, reuse the same name in two different (parallel) child
scopes, such as within one for loop and then again within another (that
isn't nested within the first).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top