Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do I get a compilation error when casting a sealed class to an interface it might implement?
    text
    copied!<p>The following code gives a compiler error CS0030 (compiled with the C# compiler of VS 2012), although the cast might succeed at runtime. Removing the <code>sealed</code> keyword, using an <code>as</code> cast, or adding an intermediate cast to <code>object</code> makes the error go away.</p> <pre><code> public interface IFunny&lt;out T&gt; { } public sealed class Funny&lt;T&gt; : IFunny&lt;T&gt; { public IFunny&lt;TOther&gt; Cast&lt;TOther&gt; () { // error CS0030: Cannot convert type Funny&lt;T&gt;' to 'IFunny&lt;TOther&gt;'. return (IFunny&lt;TOther&gt;) this; } } </code></pre> <p>It seems to me the compiler uses a heuristic for sealed classes only that is too strict in the case of generic interface implementations.</p> <p>Is it really too strict (in the sense of a bug), or is there a good reason for this error?</p> <p><strong>Update:</strong> A clarification to my question: The compiler cannot determine whether there is a relationship between <code>TOther</code> and <code>T</code> at compile time. The cast would succeed, at runtime, if <code>TOther</code> is the same or a base class of <code>T</code>, and it would fail in all other cases. This is true no matter whether <code>Funny&lt;T&gt;</code> is sealed or not.</p> <p>The C# compiler does not normally prevent casts that might succeed at runtime. (For example, I can cast an instance of static type <code>object</code> to <code>IComparable</code>, causing a runtime exception if the instance doesn't really implement that interface.) Why does it do so in this <code>sealed</code> case?</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