Weavermount
Weavermount

Reputation: 746

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?

Upvotes: 2

Views: 92

Answers (2)

Rogue
Rogue

Reputation: 676

While there are many ways to do this, one of the simplest and best ways is to define a delegate and accept that as an argument.

delegate void XYFunction(int x, int y); // define the return type and args

void ForEachXYPair(int width, int height, XYFunction func)
{
    // open your loop however
    {
        func(x, y);
    }
}

And then to call it...

ForEachXYPair(4, 4, (int x, int y) => { work; });
// OR
ForEachXYPair(4, 4, new XYFunction(AMethodForAbstractionsSake));

Upvotes: 1

Eduardo Wada
Eduardo Wada

Reputation: 2647

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);
        }
    }
}

Upvotes: 2

Related Questions