Search code examples
c#multidimensional-array

pass an array inside a multidimensional array to a function in C#


I'm trying to take a 3D array and pass an array inside there to a function, but it keeps saying an error about having the wrong number of indices inside []. I'm passing 2 values to it to return an array for a function but it's requiring me to put 3 values for a single item not an array.

public void function(int[]) {
    // does something
}

static void Main(String[] args) {
    int[,,] 3Darr = {{{1,2,3}, {4,5,6}, {7,8,9}}, {{10,11,12}, {13,14,15}, {16,17,18}}};
    
    function(arr[1,2]); // gets error for not passing 3 values
}

Solution

  • You should use jagged array (array of array of array) int[][][] instead of 3d one int[,,]:

    int[][][] arr = new int[][][] {
      new int[][] {
        new int[] {1, 2, 3},
        new int[] {4, 5, 6},
        new int[] {7, 8, 9},
      },
    
      new int[][] {
        new int[] {11, 12, 13},
        new int[] {14, 15, 16},
        new int[] {17, 18, 19},
      },
    }; 
    
    function(arr[1][2]);