I have two Arrays:
object[,] Arrayobject[][] Array.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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With