Reputation: 404
I need to assign values to 2D array but I can't find the right syntax. I tried this but is't wrong:
string[][] s2d = new string[][] {
{"val1","val2"},
{"val1bis","val2bis"}
};
Thanks
Upvotes: 1
Views: 10290
Reputation: 16956
You are almost there, just change the convention
and use [,].
, [][]
used to define Array of arrays (Jagged
arrays).
string[,] s2d = new string[,] {
{"val1","val2"},
{"val1bis","val2bis"}
};
If you want to enumerate on Multidimensional arrays you can do that but it is a flatten array.
foreach(var s in s2d)
{
// logic
}
Just access the elements in traditional way (if want).
for(int i=0;i < s2d.GetLength(0);i++)
for(int j=0;j < s2d .GetLength(1);j++)
var val = s2d [i,j];
Upvotes: 8
Reputation: 3195
If you really want array of arrays so declare array of arrays
string[][] s2d = new string[][] {
new string[] {"val1","val2"},
new string[] {"val1bis","val2bis"}
};
Upvotes: 0
Reputation: 17858
If you truly want a 2d array
string[,] s2d = new string[2,2] { {"val1","val2"}, {"val1bis","val2bis"}};
string[][] gives you a possibility of a jagged array
Upvotes: 1
Reputation: 7350
You're using an incorrect syntax:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Source: https://msdn.microsoft.com/it-it/library/2yd9wwz4.aspx
Upvotes: 2