C#: Is there a way to define method array parameter of an unkown rank?

186 views Asked by At

I'd like to define a method that accepts an array as a parameter, but this array may be of any rank. The rank will be specified by a separate parameter. Something to replace/generalize the following:

// one dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[] data) 
{
     /* code */
}

// two dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[][] data) 
{
     /* code */
}

// three dimensional array
public void WorkOnJaggedArray<T>(int rank, int[] dimensions, T[][][] data) 
{
     /* code */
}

// and so on...

Given that I have the rank and the size of each dimension passed in, I should be able to generalize the code inside my method. Is there a good way to achieve what I'm asking for?

1

There are 1 answers

2
zahid rasool On BEST ANSWER

You can use "System.Array" to manage parameters of any rank :

Create your array instance by calling Array.CreateInstance.

This will give you an instance of the Array class. Call SetValue to assign values to your array. Use GetValue to retrieve any elements of the array.

     public void WorkOnJaggedArray<T>(int rank, int[] dimensions, Array data) 
{
     /* code */
}