Click to See Complete Forum and Search --> : Multi-Dimension array initializers


savagerx
February 13th, 2003, 09:46 AM
It's me again.... I know I'm troublesome.:(

First I have this:
protected int[,] array = new int[15,10];

then I do this:
map = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,1,0,0,0,0,0,1,1,1,0,0,0,1,
8,0,0,0,0,0,0,0,1,1,1,0,0,0,1,
1,0,0,0,1,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,1,1,1,0,0,0,0,0,1,0,1,
1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,
1,0,0,0,0,1,0,0,0,0,1,1,1,0,1,
1,0,1,1,0,0,0,1,0,0,0,0,0,0,5,
1,0,1,1,0,0,0,1,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};

And the compiler says this:
CMap.cs(31,43): error CS1525: Invalid expression term ','
CMap.cs(31,44): error CS1002: ; expected
CMap.cs(31,45): error CS1002: ; expected

Multiple times. And to my surprise,
neither the books "Inside C# second edition" nor "C# language specification" actually talks about that.
MSDN is a maze to me.

Question: How to I initialize a multiple dimensional array like this?

pareshgh
February 13th, 2003, 11:50 AM
You can initialize the array upon declaration as shown in the following example:

int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:

int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:

int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
You can also assign a value to an array element, for example:

myArray[2,1] = 25;

thanx
Paresh

savagerx
February 13th, 2003, 06:40 PM
understood thanks.

pareshgh
February 14th, 2003, 11:30 AM
I know the declaration is odd than C++ but that's the way they made so...
Infact in C++ you can declare like this where as C# can't

for example
C++/C
1) int [10]a = {0};
will automatically initialize all mem. to 0

and in C# you can't


so there are mysterys.........

anyway ..

thanx
Paresh