title: How to add XmlInclude attribute dynamically
body: <p>I have the following classes</p>
  
  <pre><code>[XmlRoot]
  public class AList
  {
     public List&lt;B&gt; ListOfBs {get; set;}
  }
  
  public class B
  {
     public string BaseProperty {get; set;}
  }
  
  public class C : B
  {
      public string SomeProperty {get; set;}
  }
  
  public class Main
  {
      public static void Main(string[] args)
      {
          var aList = new AList();
          aList.ListOfBs = new List&lt;B&gt;();
          var c = new C { BaseProperty = "Base", SomeProperty = "Some" };
          aList.ListOfBs.Add(c);
  
          var type = typeof (AList);
          var serializer = new XmlSerializer(type);
          TextWriter w = new StringWriter();
          serializer.Serialize(w, aList);
      }    
  }
  </code></pre>
  
  <p>Now when I try to run the code I got an InvalidOperationException at last line saying that</p>
  
  <p>The type XmlTest.C was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.</p>
  
  <p>I know that adding a [XmlInclude(typeof(C))] attribute with [XmlRoot] would solve the problem. But I want to achieve it dynamically. Because in my project class C is not known prior to loading. Class C is being loaded as a plugin, so it is not possible for me to add XmlInclude attribute there.</p>
  
  <p>I tried also with </p>
  
  <pre><code>TypeDescriptor.AddAttributes(typeof(AList), new[] { new XmlIncludeAttribute(c.GetType()) });
  </code></pre>
  
  <p>before </p>
  
  <pre><code>var type = typeof (AList);
  </code></pre>
  
  <p>but no use. It is still giving the same exception.</p>
  
  <p>Does any one have any idea on how to achieve it?</p>