0

If have a problem to assign a value to a (array) variable in a switch statement.

I have a solution that works using "Temp" variables like myArrayTemp1 and myArrayTemp2. However I wonder why I can not use the following code.

I'm not sure if this has something to do with the scope of the variable...so here is my code :

    int x;
    x=1;


        string[,] myArray = new string[2, 2]; 


        switch (x)
        {
            case 1:
                string[,] myArrayTemp1 = { { "1", "1" }, { "1", "1" } };  //is OK
                myArray = myArrayTemp1;                                   //is OK

                myArray =  { { "1", "1" }, { "1", "1" } };                //error
                break;

            case 2:
                string[,] myArrayTemp2 = { { "2", "2" }, { "2", "2" } }; //is OK
                myArray = myArrayTemp2;                                  //is OK

                myArray =  { { "2", "2" }, { "2", "2" } };                //error
                break;

        }

MessageBox.Show ("myArray:" + myArray[0,0]);

I want to get rid of myArrayTemp1 and myArrayTemp2 and assign values to myArray in the case blocks. And I need to use the myArray = { { "1", "1" }, { "1", "1" } }; notation and not myArray[x,y] = "1"

thank you

2
  • You were given the answer to this question in your previous question, you can only use that syntax when declaring the variable. Commented Jan 9, 2015 at 15:04
  • Because this question was closed, I have answered it here. The link refers to where you asked a similar question. I hope this helps. Commented Jan 9, 2015 at 15:14

2 Answers 2

1

You just need to create the new array:

string[,] myArray = new string[2, 2];
...
myArray =  new string[2,2] { { "1", "1" }, { "1", "1" } };
Sign up to request clarification or add additional context in comments.

2 Comments

Here you are creating a new array (in the first line) then throwing it away and creating another one. new is not needed in the first line.
I know @ChrisDunaway. Let me put three points...it was just an example to show the mistake...
0

You have asked a similar question recently: C# : error using if/switch : "Local variable already defined in this scope"

I thought that it would be clear now.

You cannot use collection initializer syntax(one line) if you can't initialze it in the same line as it is declared.

But the logic seems to be that you don't need the switch at all. So why not:

string val = x.ToString();
string[,] myArray = { {val, val}, {val, val} };

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.