× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Why can I not cast to a generic interface from a type with a generic argument which is a subtype of the generic argument in my interface?

Asad Saeeduddin
Oct 08, 2015
<p>The fact that you're not allowed to do this is perfectly logical from a type safety perspective. If an <code>IController&lt;BlergRequest&gt;</code> accepts <code>BlergRequests</code> in various methods (in your example, <code>HandleRequest</code> is one such method), it stands to reason that those methods might invoke members that are <strong>only</strong> available on a <code>BlergRequest</code>, and not on a <code>Request</code>. Thus you can't assign (or cast) an <code>IController&lt;BlergRequest&gt;</code> to an <code>IController&lt;Request&gt;</code>.</p> <p>If on the other hand your interface was only <strong>returning</strong> <code>BlergRequest</code>s, and never consumed them, then it could return a <code>BlergRequest</code> to any consuming code that required a <code>Request</code>. In such a case, your interface would be <strong>covariant</strong> in <code>T</code>, and you could mark the type parameter <code>T</code> with the covariant <code>out</code> modifier. You could then assign <code>IController&lt;BlergRequest&gt;</code> wherever an <code>IController&lt;Request&gt;</code> is needed.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29113538/Why%20can%20I%20not%20cast%20to%20a%20generic%20interface%20from%20a%20type%20with%20a%20generic%20argument%20which%20is%20a%20subtype%20of%20the%20generic%20argument%20in%20my%20interface?/29113717">Stack Overflow</a>.</p>
comments powered by Disqus