title: C# XML serialization of derived classes
body: <p>Hi I am trying to serialize an array of objects which are derived from a class and I keep hitting the same error using c#. Any help is much appreciated.</p>
  
  <p>obviously this example has been scaled down for the purpose of this post in the real world Shape would contain a plethora of different shapes.</p>
  
  <p>Program.cs</p>
  
  <pre><code>namespace XMLInheritTests
  {
      class Program
      {
          static void Main(string[] args)
          {
              Shape[] a = new Shape[1] { new Square(1) };
  
              FileStream fS = new FileStream("C:\\shape.xml",
                                          FileMode.OpenOrCreate);
              XmlSerializer xS = new XmlSerializer(a.GetType());
              Console.WriteLine("writing");
              try
              {
                  xS.Serialize(fS, a);
              }
              catch (Exception e)
              {
                  Console.WriteLine(e.InnerException.ToString());
                  Console.ReadKey();
              }
              fS.Close();
              Console.WriteLine("Fin");
          }
      }
  }
  </code></pre>
  
  <p>Shape.cs</p>
  
  <pre><code>namespace XMLInheritTests
  {
      public abstract class Shape
      {
          public Shape() { }
          public int area;
          public int edges;
      }
  }
  </code></pre>
  
  <p>Square.cs</p>
  
  <pre><code>namespace XMLInheritTests
  {
      public  class  Square : Shape
      {
          public int iSize;
          public Square() { }
  
          public Square(int size)
          {
              iSize = size;
              edges = 4;
              area = size * size;
          }
      }
  }
  </code></pre>
  
  <p>Error:
  System.InvalidOperationException: The type XMLInheritTests.Square was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.</p>
  
  <p>at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA
  rray.Write2_Shape(String n, String ns, Shape o, Boolean isNullable, Boolean need
  Type) </p>
  
  <p>at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA
  rray.Write3_ArrayOfShape(Object o)</p>
  
  <p>Many Thanks</p>