Tom
Tom

Reputation: 245

C# passing an Action<> into another Action<>

I am new to delegates and I am trying to pass an Action<> as a parameter of another Action<>. For example, (with code re-usability in mind) I was attempting to make a loop action and pass other actions into it to reduce the number of loops in my code:

Action<int, Action<Control, Control>> loop = (int stop, Action<Control, Control> action) =>
{
    for (int i = 0; i < stop; i++)
    {
        for (int j = 0; j < stop; j++)
        {
            <action> pass Add;
        }
    }
};

Action<Control, Control> Add = (Control Parent, Control Child) => Parent.Controls.Add(Child);

The main objective is to be able to re-use the double for loop in such a way where I can mix and match the action inside of it with other actions.

Upvotes: 0

Views: 271

Answers (2)

ASh
ASh

Reputation: 35733

Action<int, Action<Control, Control>> loop = (int stop, Action<Control, Control> action) =>
{
    for (int i = 0; i < stop; i++)
    {
        for (int j = 0; j < stop; j++)
        {
            //// invoke action with real arguments
            // action(controlParent, controlChild);
        }
    }
};

Action<Control, Control> Add = (Control Parent, Control Child) => Parent.Controls.Add(Child);

loop(1, Add);

Upvotes: 1

Teter28
Teter28

Reputation: 524

Your action usage is not bad if you want the loop in main action using another action.

Upvotes: 0

Related Questions