I need to assign values to a two-dimensional array. I can do it using multiple "myArray[x,y]" statements but I'd like to use another method (because I'll have arrays with many lines/columns) - see code:
int x;
x = 1;
string[,] myArray = new string[2, 2];
if (x == 1)
{
//does not work : why? Would be easier to populate a big array using this
//myArray=
//{
// {"1", "1" },
// {"1", "1" }
//} ;
//works, but I need above code to work if possible
myArray[0, 0] = "1";
myArray[0, 1] = "1";
myArray[1, 0] = "1";
myArray[1, 1] = "1";
}
else if (x == 2)
//does not work
//myArray=
//{
//{"2", "2" },
//{"2", "2" }
//} ;
myArray[0, 0] = "2";
myArray[0, 1] = "2";
myArray[1, 0] = "2";
myArray[1, 1] = "2";
}
MessageBox.Show(myArray[0,0]);
thanks
As you mentioned that you need to use it in that way, then you can do a workaround by declaring a temp variable initialize the values on it and then set the temp variable to the public one, like below:
int x;
x = 1;
string[,] myArray = new string[2, 2];
if (x == 1)
{
string[,] myArrayTemp = { {"1", "1" }, {"1", "1" } };
}
else if (x == 2)
{
string[,] myArrayTemp = { {"2", "2" }, {"2", "2" } };
myArray = myArrayTemp;
}