Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use C# and Reflection to get Implemented Class type not the Interface type
    text
    copied!<p><strong>UPDATE:</strong> My "problem" was due to a bad assumption about the class I was using reflection upon. My question below is nonsensical as it doesn't act that way. But I am leaving it here in case the code snippet is useful.</p> <p>I am using reflection to generate viewmodels off of a compiled class that resides in a <strong>separate</strong> assembly. Most everything is working except the types I get back from the compiled assembly shows an interface instead of the class that is the concrete implementation of the interface.</p> <p>For example, in the compiled assembly I define a property like:</p> <pre><code> public List&lt;String&gt; strings { get; set; } </code></pre> <p>Using reflection, I have been able to generate a corresponding property (and complete class) that looks like this:</p> <pre><code> public ICollection&lt;String&gt; strings { get; set; } </code></pre> <p>I get the types doing this (severely snipped for brevity):</p> <pre><code> Type value = &lt;...some passed in type...&gt; String types = String.Join(",", value.GetGenericArguments().Select(t =&gt; t.Name).ToArray()); String.Format("{0}&lt;{1}&gt;", value.GetGenericTypeDefinition(), types); </code></pre> <p>Is there any way using the Type object to determine what concrete implementation was used for the interface returned? I am guessing no but thought I would ask.</p> <p>If there is not a way, I am thinking of using a "most likely implementation" look up for a given interface (i.e. you pass in "ICollection", I translate that into a concrete "List") unless there is a better suggestion???</p> <p>A "perfect" solution isn't necessarily required as this is used to generate Controllers, Views, and ViewModels (with automapper and Kendo UI) using T4 templates. So if there are a few things to clean up, that is fine. So any suggestions that get me close are welcome.</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