Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass action delegate as parameter in C#

Tags:

c#

delegates

I have a method which accepts an Action delegate and executes the given method as shown here:

public void ExpMethod(Action inputDel)
{
    inpuDel();
}

I can call above given method like this:

ExpMethod(() => {/*do something that matters*/});

Everything works fine. So far so good. Now I want to have a method which takes a generic Action delegate as an input parameter - like this:

public void ExpGenMethod(Action<string,int> inputDel)
{
    // I don't know how to call the supplied delegate as it requires parameters
}

Also, I am trying to call this ExpGenMethod in this way:

ExpGenMethod(("Hi",1) => {/*do something that makes sense*/});

But it shows syntax errors. Please let me know how to use generic action delegate in this case?

like image 319
gliese 581 g Avatar asked Jan 26 '17 09:01

gliese 581 g


3 Answers

Typically, you'll want the heavy lifting to happen in the ExpGenMethod and in the delegate itself you'll simply be passing the parameters to the ExpGenMethod.

using System;

public class Program
{
    public static void Main()
    {
        ExpGenMethod((options) =>
        {
            options.x = "Hi";
            options.y = 1;
        });
    }

    public static void ExpGenMethod(Action<Options> inputDel)
    {
        var options = new Options();
        inputDel(options);
        /* have access to x and y so do some thing useful with these values */
        Console.WriteLine(options.x);
        Console.WriteLine(options.y);
    }
}

public class Options
{
    public string x { set; get;}

    public int y { set; get; }
}

like image 190
Sangeet Agarwal Avatar answered Nov 15 '22 18:11

Sangeet Agarwal


The whole point of a delegate is to have a pointer to a method. Passing parameters to it while it´s being declared is therefor pointless. Instead pass the arguments for your delegate within the method that executes the delegate, in your case within ExpGenMethod:

You should do this instead:

public void ExpGenMethod(Action<string,int> inputDel)
{
    inputDel("Hi", 1);
}

And call it like this:

ExpGenMethod((x, y) => {/*do something that makes sense*/});

When executing that delegate x evaluates to "Hi" and y to 1.

like image 37
MakePeaceGreatAgain Avatar answered Nov 15 '22 18:11

MakePeaceGreatAgain


(a,b) => {/*do something that matters*/} means that a and b are parameters which are going to be specified during the call. Here you are using constant so you should do something like () => { use "Hi"; use 1;} and that would get you back to your first working example.

If you want to pass parameter you cna do it this way:

public void work()
{
    ExpGenMethod((a) => {/*do something that matters*/});
}

public void ExpGenMethod(Action<int> inputDel, int parameterToUse)
{
    inputDel(parameterToUse);
}
like image 38
Bruno Belmondo Avatar answered Nov 15 '22 17:11

Bruno Belmondo