Daniel Jones
Daniel Jones

Reputation: 109

How do i pass in a delegate as a parameter

I want to pass in a void or an int/string/bool(Which returns a value) Dynamically like so.

Delay(MyVoid);//I wont to execute a delay here, after the delay it will execute the the param/void like so...
public static void MyVoid()
{
    MessageBox.Show("The void has started!");
}
public async Task MyAsyncMethod(void V)
{
    await Task.Delay(2000);
    V()
}

ps, I have tried using Delegates but it doesn't let be use it as a parameter.

Upvotes: 0

Views: 524

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

Use an Action delegate to execute a method which returns void:

public async Task MyAsyncMethod(Action V)
{
    await Task.Delay(2000);
    V();
}

Or Func<T> for a method which returns some value

public async Task MyAsyncMethod(Func<int> V)
{
    await Task.Delay(2000);
    int result = V();
}

Upvotes: 4

Related Questions