Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable scope error - foreach loop

Tags:

scope

c#

foreach

I have the following code:

if (Current == false)
{
    foreach (var visual in visuals)
        visual.IsSelected = value;
}

Visual visual = visuals[currentIndex];

And when I compile I have this error:

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

Also, if I don't declare the visual variable, that is I replace:

Visual visual = visuals[currentIndex];

with:

visual = visuals[currentIndex];

the error is the following:

The name 'visual' does not exist in the current context

Why this behavior?

like image 443
Nick Avatar asked Oct 01 '22 03:10

Nick


2 Answers

In the first case there is ambiguity between the variables declared outside and inside.(global and local).

The compiler is confused as to what visual you are referring to. The outer one or inner one?

And in the second case, the compiler does not know what is visual.

Read more about it here;

like image 172
Amit Joki Avatar answered Oct 05 '22 12:10

Amit Joki


Why this behavior?

in your first case you have already declared the variable with name visual in your foreach loop.

in your second case you can not use the keyword visual because it does not exist. it is only available within your foreach loop.

Try This:

Visual visual1 = visuals[currentIndex];
like image 33
Sudhakar Tillapudi Avatar answered Oct 05 '22 12:10

Sudhakar Tillapudi