C# - Multidimensional array arguments in a function

Say I have a function:

static void foo(int[,] arr, arg1)
{
    //say arg1 = row - 1

    for(int row = 0; row < arr.GetLength(0); row++)
    {  
         for(int col = 0; col < arr.GetLength(1); col++)
         {
             MessageBox.Show(arr[arg1 , col]) // should be equal to arr[row-1,col]
         }
    }
}
foo(arr, "row-1"); // should be equal to arr[row-1,col]

I want to reference the loop variable with arg1.
Is this possible?
What type should arg1 be?
How do i write this?

Upvotes: 0

Views: 489

Answers (2)

Jamiec
Jamiec

Reputation: 136094

You would do this by passing Func<int,int> to the function:

static void foo(int[,] arr, Func<int,int> arg1)
{
    //say arg1 = row - 1

    for(int row = 0; row < arr.GetLength(0); row++)
    {  
         for(int col = 0; col < arr.GetLength(1); col++)
         {
             int newRow = arg1(row);
             MessageBox.Show(arr[newRow, col]) // should be equal to arr[row-1,col]
         }
    }
}

Then call it with a lamda which represents the transformation you want to do.

foo(arr, x => x-1);

The problem with this approach is that the first iteration round row it will have the value 0. By subtracting 1 from this you try to get arr[-1,col] which is outside of the bounds of the array. Im not sure what you're trying to actually achieve, so I can only guess that either you want to start the row variable at 1:

for(int row = 1; row < arr.GetLength(0); row++)

or perhaps a more complex rule for the lambda:

foo(arr, x => x>0 ? x-1 : 0);

Upvotes: 1

Peter
Peter

Reputation: 27944

static void foo(int[,] arr, int arg1){
for(int row = 0; row < arr.Length; row++)
{  
     for(int col = 0; col < arr[row].Length); col++)
     {
         if (row-1 >= 0 && arg1 < arr.Length && arr[arg1 , col] == arr[row-1,col])
             MessageBox.Show("found it!"); // should be equal to arr[row-1,col]
     }
}
}

Upvotes: 0

Related Questions