Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understood you correctly, you have an interface that provides multiple methods, each of which takes basically the same kind of delegate, but gets a different type of parameter as input. Something like this:</p> <pre><code>GetListOfSongs(..., delegate(List&lt;Song&gt; result) { ... }); GetListOfMovies(..., delegate(List&lt;Movie&gt; result) { ... }); </code></pre> <p>and you're worried about the delegate signatures that start cropping up along with the methods in the interface?</p> <p>If that's the case, then generics are what you're looking for. In fact, if your delegate signature matches my example -- that is, accepts one input parameter, returns no value -- the delegate type you want already exists in the BCL. It's called <code>Action&lt;T&gt;</code>. You could declare the methods above like so:</p> <pre><code>GetListOfSongs(..., Action&lt;List&lt;Song&gt;&gt; callback); GetListOfMovies(..., Action&lt;List&lt;Movie&gt;&gt; callback); </code></pre> <p>and you'd still only have a single delegate type, that is, <code>Action&lt;T&gt;</code>.</p> <p>Now, if you need to pass along more than one parameter, you're still covered. There exist versions of Action for up to 16 input parameters (although their signatures begin to look a bit garish: <code>Action&lt;T1, T2, T3 ...&gt;</code>).</p> <p>If you want your callback to also return a value that you'll use somewhere within your infrastructure, <code>Func&lt;T, TResult&gt;</code> is your friend (T is the type of the input parameter, TResult is the type of the value you will return from the delegate).</p> <p>As a bonus, I'd recommend you don't expose <code>List&lt;T&gt;</code> in your interfaces. If you really think all your clients will need list operations, use <code>IList&lt;T&gt;</code>, but consider <code>ICollection&lt;T&gt;</code> or even <code>IEnumerable&lt;T&gt;</code> if they won't.</p>
 

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