Note that there are some explanatory texts on larger screens.

plurals
  1. POc# generic delegate with out parameter - define and call
    primarykey
    data
    text
    <p>I'm currently refactoring an existing DAL which has a facade the user calls and an inner class that does the actual work dependent upon the ADO.Net provider to use e.g. SqlProvider, and I'm trying to ensure that code is DRY, I've done ok by using a Func so I can do:</p> <pre><code>return RunCommand(c =&gt; c.ExecuteNonQuery(commandText, parameters)); </code></pre> <p>And the RunCommand method looks like:</p> <pre><code> private T RunCommand&lt;T&gt;(Func&lt;Commands, T&gt; toRun) { return toRun(CreateCommand()); } </code></pre> <p>The <code>CreateCommand()</code> method simply builds the command object to use, this then allows me to have a single method that handles all the calls that just return the expected type e.g. DataSet, DataReader, etc</p> <p>The problem I have is that several calls on the facade provide an <code>out</code> parameter I know should be able remove the repeated code if I can use a delegate but after a lot of googling &amp; experimenting I've not managed to work out how. The code is:</p> <pre><code> Commands commands = CreateCommand(); return commands.ExecuteNonQuery(out cmd, commandText, parameters); </code></pre> <p>What I'd really like to do is be able to call:</p> <pre><code>return RunCommand(c =&gt; c.ExecuteNonQuery(out cmd, commandText, parameters)); </code></pre> <p>I've seen <a href="https://stackoverflow.com/questions/2448010/how-to-declare-a-generic-delegate-with-an-out-parameter">this</a> existing question but for the life of me I cannot work out how to turn that into what I need.</p> <p>This delegate would seem to be what I need <code>private delegate V TestOutParameter&lt;T, U, V&gt;(T a, out U b, V c);</code> but the code I've got for calling it just isn't right:</p> <pre><code> private V RunCommand&lt;T, U, V&gt;(TestOutParameter&lt;Commands, DbCommand, V&gt; commandToExecute) { DbCommand cmd; return (V)commandToExecute(CreateCommand(), out cmd); } </code></pre> <p>Can anybody help me as this has been driving me mad for a week!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload