Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>FWIW, <code>List&lt;T&gt;</code> is both <code>IEnumerable&lt;T&gt;</code> and <code>IEnumerable</code> (meaning its contents can be enumerated as instances of <code>object</code>). You can use <code>IEnumerable</code> with link like this:</p> <pre><code>object o = new List&lt;string&gt;() ; ... ((IEnumerable)o).Cast&lt;object&gt;().DoSomethingLinqy( x =&gt; ... ) ; </code></pre> <p>If you're only interested in differentiating between <code>List&lt;T&gt;</code> (and not its subtypes) and any other class (including subtypes of <code>List&lt;T&gt;</code>), then this code should do you:</p> <pre><code>object o = GetSomeObject() ; bool isGenericList = o.GetType().GetGenericTypeDefinition() == typeof(List&lt;&gt;) ; </code></pre> <p>If you need to treat <code>List&lt;T&gt;</code> and its subtypes the same, then you'll need something list this:</p> <pre><code>static bool IsInstanceOfGenericType( object o, Type genericType ) { bool isGenericTypeInstance = false ; for ( Type t = o.GetType() ; t != null &amp;&amp; !isGenericTypeInstance ; t = t.BaseType ) { isGenericTypeInstance = t.IsGenericType &amp;&amp; t.GetGenericTypeDefinition() == genericType ; } return isGenericType ; } </code></pre> <p>Which you'd use thusly:</p> <pre><code>object o = GetSomeObject() ; bool isGenericList = isInstanceOfGenericType( o , typeof(List&lt;&gt;) ) ; </code></pre> <p>If you need to be able to identify objects as implementing a generic interface, then the level of complexity goes up. The above function need to be modified such that as it runs up the inheritance hierachy, it not only checks the type, but also checks each interface implemented by the type (using <code>Type.GetInterfaces()</code>) in a way similar to the way the type check is done.</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