Pass action delegate as parameter in C#

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.


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

Tags:

C#

Delegates