2

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?

4
  • Please show us the definition of your 2D array. Commented May 13, 2015 at 23:45
  • Yes. I was using x and y to mean the iterating variable in the for loops. Where ultimately the point is to call " thePassedInlineCode(x,y) " Commented May 13, 2015 at 23:47
  • I have different representations of 2d data. This is the main reason I would like a method to simplely generate every integer coordinate and pass them to specific code Commented May 13, 2015 at 23:50
  • My real issue is picking the right kind of inline code, and using that in a method signature, and then calling it Commented May 13, 2015 at 23:54

2 Answers 2

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.