How to write OfType<Foo<Bar>>()
<p>I have generic container class I'm using that I'm trying to write a OfType routine for. However the types I'm passing in are also generics. Here's an example:</p>

<pre><code>Entities.OfType&lt;Foo&lt;Bar&gt;&gt;()
</code></pre>

<p>and my function definition:</p>

<pre><code>public IEnumerable T OfType&lt;T&gt;()
{
    foreach (var e in Values)
        if (e is T)
            yield return (T)e;
}
</code></pre>

<p>If Entities are defined as a collection of <code>Foo&lt;Base&gt;</code> I get an error <code>Foo&lt;Bar&gt;</code> does not inherit from <code>Foo&lt;Base&gt;</code>. However Bar does inherit from Base.</p>

<p>Is there a way around this limitation?</p>
