Reputation: 185
this must be answered some time in the past, however I could not a particular way that I was looking for. I want to make an array dimension of 7 x 2;
ex)
{0,0} {0,0}
{0,0}
...
...
..
.
int [,] myArray = new int[7,2];
Then I tried to treat each dimension of an array like one dimensional array. So I tried to assign values to the array this way...
int[0] = new int{ 1, 2};
I think it should then look like...
{1 , 2}
{0 , 0}
...
..
.
but i get an error.
I believe it is due to my incomplete understanding of an array class.
Upvotes: 2
Views: 9763
Reputation: 30875
You may use the proposition of Chris Shain, or stay with your approach which is Multidimensional array.
To initialize such array
int [,] myArray = new int[3,2] {{1,2},{3,4},{5,6}};
or omit the dimension parameters
int [,] myArray = new int[,] {{1,2},{3,4},{5,6}};
You problem was with accessing to the array elements, in multidimensional array you access directly to the element for example
myArray[1,1] = 7;
will change the 1 into 7;
All this and even more you will find in documentation of Arrays.
Upvotes: 1
Reputation: 385
Here's how you can do it for your case:
int [,] arr = new [,]
{
{0,1},
{1,2}
};
Upvotes: 2
Reputation: 51369
What you want is a jagged array, not a multidimentional array. Essentially, an array of arrays:
int[][] myArray = new int[7][];
int[0] = new int {1, 2};
The second "dimension" arrays are not bounded to a length of 2 however- you need to enforce that manually. This is why they are called jagged- visually, they can be of varying lengths:
{
{ 3, 2 },
{ 1, 8, 3 },
{ 9, 6, 3, 4 },
{ 4, 2, 8 },
{ 4, 9, 3, 4, 5 },
{ 2, 2 }
}
All about arrays in C# here: http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
Upvotes: 5