title: Unable to cast object of type X to Y
body: <p>I keep getting the exception “Unable to cast object of type X to Y” in some code. I’ve got an interface and two classes that implement it and it keeps throwing this error when casting from one to the other. The two classes and interface are in the same namespace in the same assembly so that’s not the issue. I created an isolated console application to figure this mess out but I can’t get them to cast to one another. I think I’ve forgotten some basic .Net rule here. Anything look off in this code to you?</p>
  
  <p>My isolated app code:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
  
          RecurringPaymentResult r = new RecurringPaymentResult();
          r.AddError("test");
          ProcessPaymentResult p = null;
          p = (ProcessPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult"
          p = (IPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult. An explicit conversion exists (are you missing a cast?)"
          p = (ProcessPaymentResult)((IPaymentResult)r); // Compiles but throws: "Unable to cast object of type RecurringPaymentResult to ProcessPaymentResult" during runtime
      }
  }
  </code></pre>
  
  <p>My core code:</p>
  
  <pre><code>public interface IPaymentResult
  {
      IList&lt;string&gt; Errors { get; set; }
      bool Success { get; }
      void AddError(string error);
  }
  
  public partial class RecurringPaymentResult : IPaymentResult
  {
      public IList&lt;string&gt; Errors { get; set; }
  
      public RecurringPaymentResult() 
      {
          this.Errors = new List&lt;string&gt;();
      }
  
      public bool Success
      {
          get { return (this.Errors.Count == 0); }
      }
  
      public void AddError(string error) 
      {
          this.Errors.Add(error);
      }
  }
  
  
  public partial class ProcessPaymentResult : IPaymentResult
  {
      private PaymentStatus _newPaymentStatus = PaymentStatus.Pending;
      public IList&lt;string&gt; Errors { get; set; }
  
      public ProcessPaymentResult() 
      {
          this.Errors = new List&lt;string&gt;();
      }
  
      public bool Success
      {
          get { return (this.Errors.Count == 0); }
      }
  
      public void AddError(string error)
      {
          this.Errors.Add(error);
      }
  
      // More properties and methods here…
  
  }
  </code></pre>