Daniel Simpkins
Daniel Simpkins

Reputation: 684

C# Initializing a Multi-dimensional array with multiple 1D arrays

I'm trying to initialize a two-dimensional array using two existing 1D arrays. Obviously, if we know the values of these arrays, we can initialize it like such:

float[,] my2DArray = new float{{1,2}, {3,4}};

However, if I try to initialize the array with variables like this:

float[] a = {1,2};
float[] b = {3,4};
float[,] my2DArray = new float{a,b};

then I get an error "A nested array initializer is expected." I'm guessing maybe this has something to do with the compiler not knowing the dimensions of the array since it won't be allocated until runtime.

So, is there any way I can work around this to do this sort of array assignment? I am targeting .NET 4.0.

Upvotes: 4

Views: 1266

Answers (2)

Abdul Saleem
Abdul Saleem

Reputation: 10612

float[] a = { 1, 2 };
float[] b = { 3, 4 };

float[,] my2DArray = new float[a.Length, b.Length];

for (int i = 0; i < a.Length; i++)
    for (int j = 0; j < b.Length; j++) 
         my2DArray[i, j] = new float[][] { a, b }[i][j];

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564353

You'll need to initialize the array yourself. You can get a performance improvement and shorter code than looping by using Buffer.BlockCopy, but can't do an inline initialization directly:

float[] a = {1,2};
float[] b = {3,4};
float[,] my2DArray = new float[a.Length, 2];

int len = a.Length * sizeof(float);
Buffer.BlockCopy(a, 0, my2DArray, 0, len);
Buffer.BlockCopy(b, 0, my2DArray, len, len);

Note that you'll have to guarantee that the source arrays are the same length for this to work.

Upvotes: 6

Related Questions