title: Why is this cast invalid when `x as Y` works fine?
body: <p>I stumbled across this odd case yesterday, where <code>t as D</code> returns a non-null value, but <code>(D)t</code> causes a compiler error.</p>
  
  <p>Since I was in a hurry I just used <code>t as D</code> and carried on, but I am curious about why the cast is invalid, as <code>t</code> really is a <code>D</code>. Can anyone shed some light on why the compiler doesn't like the cast?</p>
  
  <pre><code>class Program
  {
      public class B&lt;T&gt; where T : B&lt;T&gt; { }
  
      public class D : B&lt;D&gt; { public void M() { Console.Out.WriteLine("D.M called."); } }
  
      static void Main() { M(new D()); }
  
      public static void M&lt;T&gt;(T t) where T : B&lt;T&gt;
      {
          // Works as expected: prints "D.M called."
          var d = t as D;
          if (d != null)
              d.M();
  
          // Compiler error: "Cannot cast expression of type 'T' to type 'D'."
          // even though t really is a D!
          if (t is D)
              ((D)t).M();
      }
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> Playing around, I think this is a clearer example. In both cases <code>t</code> is constrained to be a <code>B</code> and is maybe a <code>D</code>. But the case with the generic won't compile. Does the C# just ignore the generic constraint when determining if the cast is legal? Even if it does ignore it, <code>t</code> could still be a <code>D</code>; so why is this a compile time error instead of a runtime exception?</p>
  
  <pre><code>class Program2
  {
      public class B { }
  
      public class D : B { public void M() { } }
  
      static void Main()
      {
          M(new D());
      }
  
      public static void M(B t)
      {
          // Works fine!
          if (t is D)
              ((D)t).M();
      }
  
      public static void M&lt;T&gt;(T t) where T : B
      {
          // Compile error!
          if (t is D)
              ((D)t).M();
      }
  }
  </code></pre>