Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Nope, there's no way of doing this. Any instance of <code>DictHandler</code> <em>must</em> know the exact type of <code>T</code>, including the type of <code>TKey</code> and <code>TValue</code>.</p> <p>You can use type inference to reduce how often you need to explicitly specify type arguments though, if you actually <em>have</em> an instance of the relevant dictionary. For example:</p> <pre><code>public static class DictHandler { public static DictHandler&lt;T, TKey, TValue&gt; CreateHandler&lt;T, TKey, TValue&gt; (T dictionary1, Dictionary&lt;TKey, TValue&gt; dictionary2) where T : Dictionary&lt;TKey, TValue&gt; { return new DictHandler&lt;T, TKey, TValue&gt;(); } } public class DictHandler&lt;T, TKey, TValue&gt; where T : Dictionary&lt;TKey, TValue&gt; { } </code></pre> <p>Then create it like this:</p> <pre><code>Dictionary&lt;string, int&gt; dict = new Dictionary&lt;string, int&gt;(); var handler = DictHandler.CreateHandler(dict, dict); </code></pre> <p>I believe the reason you have to have the two parameters is so that the arguments (which are all that gets used in type inference) end up corresponding with parameters which <em>directly</em> mention the type parameters. I'm not entirely sure though - and this is certainly somewhat ugly.</p> <p>Another alternative is to create a base type or base interface for A which <em>isn't</em> generic. For example, in this case (assuming we could control Dictionary) we'd create:</p> <pre><code>public interface INonGenericDictionary { // Members which don't rely on the type parameters } public class Dictionary&lt;TKey, TValue&gt; : INonGenericDictionary { ... } </code></pre> <p>then</p> <pre><code>public class DictHandler&lt;T&gt; where T : INonGenericDictionary { ... } </code></pre> <p>We can't really tell whether that's suitable in your case, but it <em>may</em> be.</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