title: Sealed keyword affects the compiler's opinion on a cast
body: <p>I have a situation where I'd like the behaviour of the compiler explained. Given a little code:</p>
  
  <pre><code>interface IFoo&lt;T&gt;
  {
      T Get();
  }
  
  class FooGetter : IFoo&lt;int&gt;
  {
      public int Get()
      {
          return 42;
      }
  }
  </code></pre>
  
  <p>The following compiles and runs:</p>
  
  <pre><code>static class FooGetterGetter
  {
      public static IFoo&lt;T&gt; Get&lt;T&gt;()
      {
          return (IFoo&lt;T&gt;)new FooGetter();
      }
  }
  </code></pre>
  
  <p>If we make a change to the signature of the <code>Foo</code> class and add the <code>sealed</code> keyword:</p>
  
  <pre><code>sealed class FooGetter : IFoo&lt;int&gt; // etc
  </code></pre>
  
  <p>Then I get a compiler error on the following line:</p>
  
  <pre><code> return (IFoo&lt;T&gt;)new FooGetter();
  </code></pre>
  
  <p>Of:</p>
  
  <blockquote>
    <p>Cannot convert type 'MyNamespace.FooGetter' to 'MyNamespace.IFoo&lt;T&gt;'</p>
  </blockquote>
  
  <p>Can someone explain what is happening here with regards to the <code>sealed</code> keyword? This is C# 4 against a .NET 4 project in Visual Studio 2010.</p>
  
  <p><strong>Update:</strong> interestingly enough I stumbled on that part of the behaviour when I was wondering why the following code fixes it when <code>sealed</code> is applied:</p>
  
  <pre><code>return (IFoo&lt;T&gt;)(IFoo&lt;int&gt;)new FooGetter();
  </code></pre>
  
  <p><strong>Update:</strong> just for clarification, it all runs fine when the type of <code>T</code> requested is the same as the type of <code>T</code> used by the concrete type. If the types differ, the cast fails at runtime with something like:</p>
  
  <blockquote>
    <p>Unable to cast object of type 'MyNamespace.StringFoo' to type
    'MyNamespace.IFoo`1[System.Int32]'</p>
  </blockquote>
  
  <p>In the above example, <code>StringFoo : IFoo&lt;string&gt;</code> and the caller asks to get an <code>int</code>.</p>