Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling generic method with a type argument known only at execution time
    text
    copied!<p>Edit:</p> <p>Of course my real code doesn't look exactly like this. I tried to write semi-pseudo code to make it more clear of whay I wanted to do.</p> <p>Looks like it just messed things up instead.</p> <p>So, what I actually would like to do is this:</p> <pre><code>Method&lt;Interface1&gt;(); Method&lt;Interface2&gt;(); Method&lt;Interface3&gt;(); ... </code></pre> <p>Well ... I thought that maybe I could turn it into a loop using reflection. So the question is: How how do I do it. I have <em>very</em> shallow knowledge of reflection. So code examples would be great.</p> <p>The scenario looks like this:</p> <pre><code>public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() { Assembly assembly = Assembly.GetExecutingAssembly(); var interfaces = from i in assembly.GetTypes() where i.Namespace == "MyNamespace.Interface" // only interfaces stored here select i; foreach(var i in interfaces) { Method&lt;i&gt;(); // Get compile error here! } </code></pre> <p><br><br></p> <hr> <p>Original post:</p> <p>Hi!</p> <p>I'm trying to loop through all interfaces in a namespace and send them as arguments to a generic method like this:</p> <pre><code>public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() { Assembly assembly = Assembly.GetExecutingAssembly(); var interfaces = from i in assembly.GetTypes() where i.Namespace == "MyNamespace.Interface" // only interfaces stored here select i; foreach(var interface in interfaces) { Method&lt;interface&gt;(); // Get compile error here! } } </code></pre> <p>The error I get is "Type name expected, but local variable name found". If I try</p> <pre><code>... foreach(var interface in interfaces) { Method&lt;interface.MakeGenericType()&gt;(); // Still get compile error here! } } </code></pre> <p>I get "Cannot apply operator '&lt;' to operands of type 'method group' and 'System.Type'" Any idea on how to get around this problem? </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