Mehdi Bugnard Mehdi Bugnard - 2 months ago 10x
C# Question

How extend a jagged array

I tried to extend a jagged array with

with no success.
I don't know why it's not working, I've got no exception but the range of my array not change.
Here is the code I use:

public World( ushort[][][] worldMatrice)
// OldWith = 864
ushort OldWidth = (ushort)worldMatrice.GetLength(0);

// Extend the matrice to (1024) => only the first level [1024][][]
worldMatrice.ToList().Add(new ushort[1024- OldWidth][]);
// NewWidth = 864 , and should be 1024 ...
ushort NewWidth = worldMatrice.getLenght(0);


Array.AddRange() doesn't change the dimensions of an Array, and Array.Length will always return the max number of elements the array can hold, not the total number of non-null elements inside it.

If you're looking to change the dimensions of the Array, you're likely going to need to transfer the values from the old array to a new Array with dimensions you want.

int[] newArray = new int[1024];
Array.Copy(oldArray, newArray, oldArray.Length);

To get the number of non-null elements in the array, use something like

int count = array.Count(s => s != null);