Search code examples
c#multidimensional-arrayinline-code

C# trouble passing inline code


Hey I know there are a lot of questions already that contain the answer I need, but I'm having a hard time sifting between Func/Action/Delegate/Lambda, and as a javascript guy it all feels needlessly complex.

I'm working with 2d arrays and would like to write a method that accepts int width, int height, and any form of inline code to be called with every x/y pair. The point is just to avoid the bugs and time from writing a nested for loop over and over. But I'm unsure about the proper type of inline code to use, or what that looks like. I've tried a bunch of combos but can't make it work out.

What signature should I use on the method, and how do I call that?


Solution

  • I usually use action as the type parameter, and a lambda when calling:

    ForEachPair(5, 5, (x, y) =>
    {
        Console.Write(x + "," + y);
    });
    
    public void ForEachPair(int width, int height, Action<int, int> callback)
    {
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                callback(i, j);
            }
        }
    }