title: c# runtime polymorphism with abstract base class
body: <p>I am trying to clean up an existing code base, and am having trouble with using a generic reference name to the different derived classes of an abstract class.</p>
  
  <p>For instance:</p>
  
  <pre><code>public abstract class Base&lt;T&gt; : Utilities.CommonRequiredObject
  {
      protected List&lt;T&gt; RawContents = new List&lt;T&gt;();
      .
      .
  
      public abstract void LoadContents(List&lt;T&gt; Contents);        // Each Class needs to load and process differently
      protected List&lt;T&gt; Contents;
  
      public virtual void DoSomething()           // Default here for common use. Defined in Each class for its specifics (if needed)
      {
      ...
      }
      public abstract List&lt;T&gt; FunctionToGetContents();
  
  }
  
  public class FOO : Base&lt;string&gt;
  {
      public override void DoSomething() ...
      public override List&lt;string&gt; FunctionToGetContents() ...
  }
  
  public class BAR : Base&lt;byte&gt;
  {
      public override void DoSomething() ...
      public override List&lt;byte&gt; FunctionToGetContents() ...
  }
  </code></pre>
  
  <p>Main Logic to try to use common variable.  I want to create a new class to use, but want to use it then in a runtime polymorphic way. As the classes have the common functionality, and have overrides where needed, I want to be able to create an instance, and then use it:</p>
  
  <pre><code>IE: Base&lt;T&gt; ObjectToUse;
  </code></pre>
  
  <p>This way, I can simply refer to the <code>ObjectToUse</code> in the following code and call common methods.  As I inherited some common routines from another base class, I am not sure if I can use an interface or not.</p>
  
  <pre><code>if(variable)
  {
      FOO ObjectToUse = new FOO();
  }
  else
  {
      BAR ObjectToUse = new BAR();
  }
  
  ObjectToUse.LoadContents(ObjectToUse.FunctionToGetContents());
  ObjectToUse.DoSomething();
  ...
  </code></pre>
  
  <p>Edit:
  Based on the comments I received quickly (thanks again everyone) would it be better than to remove the Generic (<code>Base&lt;T&gt;</code>) and have the classes all of type Base(), then I could define the <code>ObjectToUse</code> simply as <code>Base ObjectToUse;</code> I believe.</p>