title: XML serialize base class without knowing derived class
body: <p>I know that an <code>XmlSerializer</code> will throw an exception if the passed in type does not match the type from when the serializer was created.</p>
  
  <p>My question is: Is it possible to serialize a base type without knowing the derived type? Consider this scenario:</p>
  
  <p>The following classes are in a <strong>top-level domain and have few or no dependencies</strong>:</p>
  
  <pre><code>public class Serializer
  {
      private static string Serialize(Base baseData)
      {
          var serializer = new XmlSerializer(typeof(Base));
          var sb = new StringBuilder();
          using (var writer = XmlWriter.Create(sb))
          {
              serializer.Serialize(writer, baseData);
          }
          return sb.ToString();
      }
  
      private static string Deserialize(...) { ... }
  }
  
  public class Base
  {
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>The following derived class has <strong>additional dependencies</strong> on things like UI components, composition, etc. (more on this later):</p>
  
  <pre><code>[Export(typeof(IMyComponent))]
  public class Derived : Base, IMyComponent, INotifyPropertyChanged
  {
      public new string Name
      { 
          get { return base.Name; }
          set
          {
              base.Name = value;
              NotifyPropertyChanged("Name");
          }
      }
  }
  </code></pre>
  
  <p>If I invoke the serializer like this:</p>
  
  <pre><code>Base myData = new Derived();
  myData.Name = "Foo bar";
  Serializer.Serialize(myData);
  </code></pre>
  
  <p>It throws an exception because I passed in a <code>Derived</code>, even though the parameters and serializer are explicitly set to <code>Base</code>. All I want is to serialize <code>Base</code>, I don't care about whatever is in <code>Derived</code>.</p>
  
  <p>My goal here is to create the derived class with a UI, but <em>only serialize the base class</em>. The reason is that I am deserializing the XML in a <strong>separate assembly that must not contain additional dependencies beyond the .NET framework.</strong> The serializer and base objects are recreated/copied into this isolated assembly so that the namespaces and types will match, so that when deserialization occurs, the types will be deserialized correctly. But I can't include a copy of <code>Derived</code> because it has dependencies on UI, MEF, other third party libraries, etc.</p>
  
  <p>So, how can I force the serializer to serialize the base class even if I pass in a derived class? Again, I don't care if I lose the information in <code>Derived</code>, all I am concerned about is <code>Base</code>.</p>