r3plica
r3plica

Reputation: 13367

c# Generic function as a parameter

I have this function:

private async Task Wizardry<T>(Func<T theParameter, Task> method)
{
    try
    {
        await method(theParameter);
    }
    catch
    { }
}

and the way I see it working is like this:

await this.Wizardry<Email>(this.emailProvider.SendAsync(email));
await this.Wizardry<Log>(this.SaveLog(log));

but obviously that does not work. Does anyone know how I can achieve this?

Upvotes: 0

Views: 705

Answers (3)

Patrick Hofman
Patrick Hofman

Reputation: 156978

You are attempting to create a Func where you want to pass in parameters while you haven't got any parameters to pass in.

A non-generic Func<Task> will do:

await this.Wizardry(() => this.emailProvider.SendAsync(email));
await this.Wizardry(() => this.SaveLog(log));

private async Task Wizardry(Func<Task> method)
{
    await method();
}

Upvotes: 2

Dennis_E
Dennis_E

Reputation: 8894

I can see 2 possibilities:

private async Task Wizardry(Func<Task> method) {
    try {
        await method();
    } catch {
    }
}

Which is called with:

this.Wizardry(() => this.emailProvider.SendAsync(email));

Or

private async Task Wizardry<T>(Func<T, Task> method, T theParameter) {
    try {
        await method(theParameter);
    } catch {
    }
}

Which is called with:

this.Wizardry(this.emailProvider.SendAsync, email);

Upvotes: 1

3615
3615

Reputation: 3875

Is this what you need:

    private async Task Wizardry<T>(Func<T, Task> method, T theParameter)
    {
        try
        {
            await method(theParameter);
        }
        catch
        {
        }
    }

And invoke it like:

await this.Wizardry<string>((z)=> Task.Run(()=>Console.WriteLine(z)), "test");

Upvotes: 5

Related Questions