title: How to use XmlInclude to serialize IEnumerable
body: <p>I've run into an issue with serializing an <code>IEnumerable</code> with the <code>XmlSerializer</code>. Since <code>IEnumerable</code> represents a list of <code>object</code>, <code>XmlSerializer</code> doesn't know ahead of time what types it needs to serialize. But because it needs to know, it throws an <code>InvalidOperationException</code> when it encounters a type other than <code>object</code>.</p>
  
  <blockquote>
    <p>The type Foo.Bar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.</p>
  </blockquote>
  
  <p>The <code>XmlIncludeAttribute</code> is intended to be applied to a method to indicate that the return value can be a certain type. However, <code>IEnumerable</code> has no method that I could put the attribute on.</p>
  
  <p>I tried applying them to <code>GetEnumerator</code>:</p>
  
  <pre><code>public class Bar : IEnumerable
  {
      private List&lt;object&gt; list;
  
      public Bar()
      {
      }
  
      [XmlInclude(typeof(Bar))]
      [XmlInclude(typeof(ChildBar))]
      public IEnumerator GetEnumerator()
      {
          return list.GetEnumerator();
      }
  
      public void Add(Bar bar)
      {
          list.Add(bar);
      }
  
      public void Add(ChildBar childBar)
      {
          list.Add(childBar);
      }
  
      // used for deserialization
      public void Add(object o)
      {
          if (o is Bar || o is ChildBar)
          {
              list.Add(o);
          }
      }
  
      // more irrelevant stuff
  }
  
  public class ChildBar
  {
      public ChildBar()
      {
      }
  
      // more irrelevant stuff
  }
  </code></pre>
  
  <p>That didn't solve it, and I have no idea where else to use the attributes.</p>
  
  <p>Where should I put them? Can I work around it without them? Can I avoid writing my own enumerator?</p>