title: Automatic creation of derived classes from an associated settings class?
body: <p>I'm trying to automatically instantiate the correct derived class based on the derived settings class.</p>
  
  <p>Here I have the main base class along with a base settings class</p>
  
  <pre><code>public abstract class BaseClass
  {
      public BaseClass() { }
  
      public abstract BaseClassSettings Write();
  }
  
  public class BaseClassSettings
  {
  
  }
  </code></pre>
  
  <p>Now here are my derive classes and their settings classes</p>
  
  <pre><code>public class DerivedFoo : BaseClass
  {
      public DerivedFoo(DerivedFooSettings settings) 
      { 
           // Apply settings
      }
  
      public override BaseClassSettings Write()
      {
          DerivedFooSettings settings = new DerivedFooSettings();
  
          return settings;
      }
  }
  
  public class DerivedFooSettings : BaseClassSettings
  {
  
  }
  
  public class DerivedBar : BaseClass
  {
      public DerivedBar(DerivedBarSettings settings) 
      { 
           // Apply settings
      }
  
      public override BaseClassSettings Write()
      {
          DerivedBarSettings settings = new DerivedBarSettings();
  
          return settings;
      }
  }
  
  public class DerivedBarSettings : BaseClassSettings
  {
  
  }
  </code></pre>
  
  <p>I can save all the derived class settings in one array</p>
  
  <pre><code>DerivedFoo foo = new DerivedFoo();
  DerivedBar bar = new DerivedBar();
  
  BaseClassSettings[] s = new BaseClassSettings[2];
  s[0] = foo.Write();
  s[1] = bar.Write();
  </code></pre>
  
  <p>which serializes to disc in XML format.</p>
  
  <p>How can I automatically instantiate the derived classes based on the derived settings classes?</p>
  
  <p>So if the array element is a DerivedBarSettings class create a new instance of the DerivedBar class.</p>
  
  <p>I would like to do this without using an ever increasing number of else if statements depending on the number of classes. </p>
  
  <pre><code>if (BaseClassSettings is DerivedFooSettings)
      new DerivedFoo(settings)
  else if (BaseClassSettings is DerivedBarSettings) 
      new DerivedBar(settings)
  </code></pre>
  
  <p>How can this be done?</p>
  
  <p>===============================================================================</p>
  
  <p>[EDIT]</p>
  
  <p>Here's what I am using:</p>
  
  <pre><code>[
      XmlInclude(typeof(DerivedSettingsClassA)),
      XmlInclude(typeof(DerivedSettingsClassB)),
      XmlInclude(typeof(DerivedSettingsClassC)),
      XmlInclude(typeof(DerivedSettingsClassD)),
      XmlInclude(typeof(DerivedSettingsClassE)),
  ]
  public abstract class BaseSettingsClass
  {
      public abstract DerivedClass Load(Game1 game, OutputDimensionSettings settings);
  }
  </code></pre>
  
  <p>The only downside to this is that I have to explicitely define XmlInclude for all derived classes.</p>