-3

I'm trying to pass a Func<TResponse, T1, T2> through to this method. I keep getting a syntax error for "method()" though. It says it needs two arguments which makes sense, but how do I pass it to the method? I've assigned them as T1 and T2.

How can I make this return the TResponse as well?

The way I'm calling it (the func I want to use to call the method).

_service.Count(fileDate (DateTime), cycle int));

What am I doing wrong here?

public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method) where TResponse : class
{
    try
    {
        Log(id, Name);
        TResponse x = method();
        Log(id, Name);
    }
    catch (Exception ex)
    {
        Log(id, Name);
        throw;
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
magna_nz
  • 1,243
  • 5
  • 23
  • 42
  • 1
    Voting to close this as a typo because you're just trying to call a method without the required number of parameters. – DavidG Jul 30 '18 at 23:56

2 Answers2

3

I'm guessing you actually want this....

public TResponse ExecuteAndLog<TResponse>(Guid id, string Name, Func<TResponse> method) where TResponse : class
{
    try
    {
        Log(id, Name);
        TResponse x = method();
        Log(id, Name);
    }
    catch (Exception ex)
    {
        Log(id, Name);
        throw;
    }
}

And you'd call it with

var response = ExecuteAndLog(someGuid, someName, () => _service.Count(fileDate, cycle));

This way you only need one prototype of ExecuteAndLog. If you include the inputs in the Func (as you did in your example), you'd have to pass the arguments through, and you'd need a different version of ExecuteAndLog for each possible service call signature.

Note: Whenever you use a lambda expression this way, be careful of closures.

John Wu
  • 50,556
  • 8
  • 44
  • 80
2

If method should receive two parameters, you need to pass them:

public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method, T1 arg1, T2 arg2) where TResponse : class
{
    try
    {
        Log(id, Name);
        TResponse x = method(arg1, arg2);
        Log(id, Name);

        return x;
    }
    catch (Exception ex)
    {
        Log(id, Name);
        throw;
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120