title: Why XML-Serializable class need a parameterless constructor
body: <p>I'm writing code to do Xml serialization. With below function.</p>
  
  <pre><code>public static string SerializeToXml(object obj)
  {
      XmlSerializer serializer = new XmlSerializer(obj.GetType());
      using (StringWriter writer = new StringWriter())
      {
          serializer.Serialize(writer, obj);
          return writer.ToString();
      }
  }
  </code></pre>
  
  <p>If the argument is a instance of class without parameterless constructor, it will throw a exception.</p>
  
  <blockquote>
    <p>Unhandled Exception:
    System.InvalidOperationException:
    CSharpConsole.Foo cannot be serialized
    because it does not have a
    parameterless constructor.    at
    System.Xml.Serialization.TypeDesc.CheckSupported()
    at
    System.Xml.Serialization.TypeScope.GetTypeDesc(Type
    type, MemberInfo sourc e, Boolean
    directReference, Boolean throwOnError)
    at
    System.Xml.Serialization.ModelScope.GetTypeModel(Type
    type, Boolean direct Reference)    at
    System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type
    type , XmlRootAttribute root, String
    defaultNamespace)    at
    System.Xml.Serialization.XmlSerializer..ctor(Type
    type, String defaultName space)    at
    System.Xml.Serialization.XmlSerializer..ctor(Type
    type)</p>
  </blockquote>
  
  <p>Why must there be a parameterless constructor in order to allow xml serialization to succeed?</p>
  
  <p>EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.</p>