Search code examples
c#functiongenericsexecution

Trying to call a function in C# using a generic Execution Helper function returning an out value depending on the result of that function


public class ExecutionUtility
{
    public static TIn2 ExecutionHelper<TIn1, TIn2>(Func<TIn1, out TIn2, int> function, TIn1 input)
    {
        TIn2 output = default(TIn2);
        int result = function(input, out output); // the out keyworkd is not accepted apparently

        if (result == 0)
        {
            return output;
        }
        else
        {
            throw new FunctionExecutionException(result);
        }
    }

}

Just some exeption code:

public class FunctionExecutionException : Exception
{
    public int ErrorCode { get; }

    public FunctionExecutionException(int errorCode)
    : base($"Function execution failed with error code: {errorCode}")
    {
        ErrorCode = errorCode;
    }
}

An example of a static function that returns a int resul and also a string output parameter

public static int myfunction(int input, out string output)
{
    if (input > 0)
    {
        output = "OUTPUT_VALUE_1";
        return 0;
    }
    else
    {
        output = "OUTPUT_VALUE_2";
        return -1;
    }
}

Now using the Execution Helper function. For some reason the out parameter doesn't seem to be authorized and my code does not compile.

return ExecutionUtility.ExecutionHelper<int, string>(PRD_GCAPI.myfunction, this.Index);

Solution

  • You are able to define delegate types:

    public delegate int FuncHelper<TIn1, TIn2>(TIn1 a, out TIn2 b);
    
    public static TIn2 ExecutionHelper<TIn1, TIn2>(FuncHelper<TIn1, TIn2> function, TIn1 input)