C # general delegate with out parameter - definition and call

I am currently reorganizing an existing DAL that has a facade called by the user and an inner class that does the actual work depending on the ADO.Net provider for use, for example. SqlProvider, and I'm trying to make sure that the code is DRY, I did fine using Func so that I can:

return RunCommand(c => c.ExecuteNonQuery(commandText, parameters));

And the RunCommand method looks like this:

    private T RunCommand<T>(Func<Commands, T> toRun)
    {
        return toRun(CreateCommand());
    }

The method CreateCommand()simply creates a command object to use, so this allows me to have a single method that handles all calls that return only the expected type, for example. DataSet, DataReader, etc.

The problem is that several calls on the facade provide a parameter outthat, as I know, should remove duplicate code if I can use a delegate, but after a lot of searching and experimenting, I was not able to work out how. The code:

 Commands commands = CreateCommand();
 return commands.ExecuteNonQuery(out cmd, commandText, parameters);

What I really would like to do is call:

return RunCommand(c => c.ExecuteNonQuery(out cmd, commandText, parameters));

I saw this existing question, but for life I can’t understand how to turn this into what I need.

I seem to need this delegate, private delegate V TestOutParameter<T, U, V>(T a, out U b, V c);but the code that I have to call it is wrong:

    private V RunCommand<T, U, V>(TestOutParameter<Commands, DbCommand, V> commandToExecute)
    {
        DbCommand cmd;
        return (V)commandToExecute(CreateCommand(), out cmd);
    }

Can someone help me since it drove me crazy for a week!

+5
source share
1 answer

. , , Func, :

private delegate V TestOutParameter<T, U, V>(T a, out U b, V c);

:

private delegate V TestOutParameter<T, U, V>(T a, out U b);

:

private delegate TResult FuncOut<T1, T2, TResult>(T1 arg1, out T2 arg2)
+11

All Articles