tzumd
tzumd

Reputation: 33

copy values from Object[,] Array to Object[][] Array

I have two Arrays:

I want to copy the values from the object[,] array to the object[][] array.

I have tried something like that

object[,] array1 = new object[arraySize, 4]; //Here are some values inside
object[][] array2 = new object[arraySize][];


for (int i = 0; i < arraySize; i++)
{
    array2[i][0] = array1[i, 0];
    array2[i][1] = array1[i, 1];
    array2[i][2] = array1[i, 2];
    array2[i][3] = array1[i, 3];
    
}

But I got a NullReferenceException:

Object reference not set to an instance of an object.

Upvotes: 3

Views: 72

Answers (2)

Mo B.
Mo B.

Reputation: 5827

Try this:

for (int i = 0; i < array1.GetLength(0); i++)
{
    array2[i] = new object[array1.GetLength(1)]; // array2[i] is null initially
    for(int j = 0; j < array1.GetLength(1); j++) {           
        array2[i][j] = array1[i, j];
    }
}

Try it out here: https://dotnetfiddle.net/f1XUXI

Upvotes: 1

Pedro Perez
Pedro Perez

Reputation: 932

array2[i][0] = array1[i, 0];

Here you have a null reference exception because array2[i] is null. You need to initialize each element of array2 before you can use.

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

microsoft documentation

// In your code, `arraySize` correspond to the numbers of rows in a multidimensional array. 
// In this example, rows = 2, columns = 4.
object[,] array1 = new object[2, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
object[][] array2 = new object[2][] { new object[4], new object[4] };

for (int x = 0; x < 2; x++)
{
    for (int y = 0; y < 4; y++)
    {
        array2[x][y] = array1[x, y];
    }
}

// print array2
for (int i = 0; i < array2.Length; i++)
{
    Console.WriteLine(string.Join(",", array2[i]));
}

Console.ReadLine();
       

Upvotes: 1

Related Questions