title: Factory for lists
body: <p>My apologies if this looks very much like a similar question I asked a few weeks back; I am learning. </p>
  
  <p>I have a function that should return a List of objects - somewhat like a Factory. In the example below I have two classes Truck and Car who both inherit from the superclass Vehicle. The function does not work, but it should show what I want to accomplish. </p>
  
  <p>EDIT: Forgot to say HOW it did not work. Well, the function creates a List of, for example, Trucks, but cannot return it since the return value must be a List of <em>Vehicle</em>. I do not know how to convert the created list or even if it <em>can</em> be converted.</p>
  
  <p>Obviously I am primarily asking for advice how to get the damned thing to work! But I would also appreciate any ideas on how to get it more scalable - to have a "case" statement for every possible Vehicle class does not make me happy.</p>
  
  <p>The v.Populate function is just there to fill the object with data from the DataReader. Should not affect the problem at hand.</p>
  
  <p>Calling the function, in this instance I want a List with Truck objects:  <strong>return PopulateList("Truck", gc);</strong></p>
  
  <pre><code>private List&lt;Vehicle&gt; PopulateList(String type, GenericConnection gc)
  {
      Vehicle v;
      var ret = new List&lt;Vehicle&gt;();
      var r = gc.ExecuteReader();
      while (r.Read())
      {
          switch (type)
          {
              case "Truck":
                  v = new Truck();
                  break;
              case "Car":
                  v = new Car();
                  break;
              default:
                  throw new ArgumentException("Unknown Vehicle: " + type, "type");
          }
          v.Populate(r);
          ret.Add(v);
      }
      r.Close();
      return ret;
  }
  </code></pre>
  
  <p>For clarity, here is a copy of the same function but now all non-essential code (mostly concerning the DataReader) is stripped away. The return value should be a List with exactly one empty object in it.</p>
  
  <pre><code>private List&lt;Vehicle&gt; PopulateList(String type)
  {
      Vehicle v;
      var ret = new List&lt;Vehicle&gt;();
      switch (type)
      {
          case "Truck":
              v = new Truck();
          case "Car":
              v = new Car();
          }
      }
      ret.Add(v);
      return ret;
  }
  </code></pre>