title: Use the XmlInclude or SoapInclude attribute to specify types that are not known statically
body: <p>I've got a very strange problem when working with .NET's <code>XmlSerializer</code>. </p>
  
  <p>Take the following example classes:</p>
  
  <pre><code>public class Order 
  {
      public PaymentCollection Payments { get; set; }
  
      //everything else is serializable (including other collections of non-abstract types)
  }
  
  public class PaymentCollection : Collection&lt;Payment&gt;
  {
  }
  
  public abstract class Payment 
  {
      //abstract methods
  }
  
  public class BankPayment : Payment
  {
      //method implementations
  }
  </code></pre>
  
  <p>AFAIK, there are three different methods to solve the <code>InvalidOperationException</code> that's caused by the serializer not knowing about the derived types of <code>Payment</code>.</p>
  
  <p><strong>1. Adding <code>XmlInclude</code> to the <code>Payment</code> class definition:</strong></p>
  
  <p>This is not possible due to all classes being included as external references over which I have no control of.</p>
  
  <p><strong>2. Passing the derived types' types during creation of the <code>XmlSerializer</code> instance</strong></p>
  
  <p>Doesn't work.</p>
  
  <p><strong>3. Defining <code>XmlAttributeOverrides</code> for the target property in order to override the property's default serialization (as explained in <a href="https://stackoverflow.com/questions/2689566/how-to-add-xmlinclude-attribute-dynamically">this SO post</a>)</strong></p>
  
  <p>Also doesn't work (<code>XmlAttributeOverrides</code> initialization follows).</p>
  
  <pre><code>Type bankPayment = typeof(BankPayment);
  
  XmlAttributes attributes = new XmlAttributes();
  attributes.XmlElements.Add(new XmlElementAttribute(bankPayment.Name, bankPayment));
  
  XmlAttributeOverrides overrides = new XmlAttributeOverrides();
  overrides.Add(typeof(Order), "Payments", attributes);
  </code></pre>
  
  <p>The appropriate <code>XmlSerializer</code> constructor would then be used.</p>
  
  <p>NOTE: by <em>doesn't work</em> I mean the <code>InvalidOperationException</code> (<em><code>BankPayment</code> was not expected...</em>) is thrown.</p>
  
  <p>Can anyone shed some light on the subject? How would one go about and debug the issue further? </p>