Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : error using if/switch : "Local variable already defined in this scope" [duplicate]

Tags:

arrays

c#

I'm new to C# and my problem is probably simple, but I don't get it:

I need to assign some values to an array depending on a condition. So I can use "if" of "switch" statement for checking the condition.

However,if I use "switch" then I get an error "Local variable already defined in this scope".

And if I use "if" then I get an error "does not exist in current context"

Example:

int x;
x=1;

//1:
//a)  does work...
if (x==1)
{
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
}
else
{
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
}


//b) but this does not work
MessageBox.Show(arraySpielfeld2d[0,0]);  //error: does not exist in current context


//2) doesn't work at all
switch (x)
    {

    case 1:
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
        break;


    case 2:
        string[,] arraySpielfeld2d =    //error:Local variable already defined in this scope
        {
         {"2", "2" },
         {"2", "2" }
        };
        break;

    }

So using "if" I can at least populate the array (1a)...but I can not access the array elements (1b)... Using "switch" doesn't work at all.

So how could I assign and then access values to an array depending on a condition (if/switch)?

I use Visual Studio 2010.

thanks

like image 688
Spacewalker Avatar asked Sep 07 '25 15:09

Spacewalker


1 Answers

What you're encountering here is the scope of the variables.

Any variable declared inside a block { } is only visible within that block. Any code after the block will not be able to see it. Thus, your if-using code declares the variable, but it does so inside those two branches so the code immediately afterwards can't see it at all.

The solution is to declare the variable before the if, assign it in the blocks, then you can use it afterwards (just make sure you don't leave a path where it can end up unassigned, unless you're prepared for that possibility when you use it).

The switch code doesn't work because there's only one block for the whole statement, and you declare the same variable name twice within it.

It still has the same scoping problem though, because that variable won't be visible outside the switch block. Again, the solution is to declare the variable first, then assign it within the switch.

like image 193
Matthew Walton Avatar answered Sep 10 '25 20:09

Matthew Walton