3

I have two Arrays:

  • an object[,] Array
  • an object[][] 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.

3
  • You got the direction of your assignments wrong. Commented Sep 24, 2020 at 8:37
  • And why are you using arrayCounter2 and not just i? Commented Sep 24, 2020 at 8:38
  • i have edited, thank you Commented Sep 24, 2020 at 8:42

2 Answers 2

1
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();
       
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

thaks, but got the same exception: NullReferenceException: Object reference not set to an instance of an object.
I added a fiddle so you can see it in action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.