Search code examples
c#arraysmultidimensional-arrayrowindices

C# rows of multi-dimensional arrays


In the C# programming language, how do I pass a row of a multi-dimensional array? For example, suppose I have the following:

int[,] foo;
foo = new int[6,4];
int[] least;
least = new int[6];

for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(ref foo[i]);     //How do I pass the ith row of foo???
}

Also, could anyone explain to me the benefit of having rectangular and jagged arrays in C#? Does this occur in other popular programming languages? (Java?) Thanks for all the help!


Solution

  • You can't pass a row of a rectangular array, you have to use a jagged array (an array of arrays):

    int[][] foo = new int[6][];
    
    for(int i = 0; i < 6; i++)
        foo[i] = new int[4];
    
    int[] least = new int[6];
    
    for(int i = 0; i < 6; i++)
        least[i] = FindLeast(foo[i]);
    

    EDIT
    If you find it so annoying to use a jagged array and desperately need a rectangular one, a simple trick will save you:

    int FindLeast(int[,] rectangularArray, int row)