title: Cast object and return from method
body: <p>I have following classes as below:</p>
  <pre><code>class Animal {
       public int Id { get; set; }
       public string Name { get; set; }
  }
  
  class Dog : Animal {
  }
  
  class Cat : Animal {
      public int CatType { get; set; }
      public int CatLoc { get; set; }
  }
  </code></pre>
  <p>As shown <code>Cat</code> contains <code>two more fields</code>. I have method that returns collection of <code>Animals</code> and argument <code>Sector</code>. This method has to return either colection of <code>Cat</code> or collection of <code>Dog</code> depending on <code>Sector</code>. If passed <code>Sector = Sector.RT</code> my method needs to query additionally two fields for <code>Cat</code> from <code>database</code>. I got problems with converting and filling <code>animal variable</code> when <code>Sector = Sector.RT</code> in <code>if (sector == sector.RT) ...</code> because <code>CatType</code> and <code>CatLoc</code> are unknown at this point and then correctly returns valid object. How should i do this properly? Hope explained well.</p>
  <pre><code>public IEnumerable&lt;Animal&gt; GetData(Sector sector)
  {
      var animal = new Animal();
      var additionalCat = $&quot;CatType, CatLoc &quot;;
      
      var query = $&quot;SELECT Id, Name, &quot; +
                  $&quot;{(sector == SectorEnum.RT ? additionalCat : string.Empty)} &quot; +
                  $&quot;FROM Animals&quot;;
                  
      using var conn = Context.GetDbConn();
      using var cmd = Context.GetCommand(query, conn, CommandType.Text);
      using var reader = cmd.ExecuteReader();
      while (reader.Read())
      {
          animal = new Animal();
          for (var i = 0; i &lt; reader.FieldCount; i++)
          {
              if (i == 0) animal.Id = (int)reader[i];
              if (i == 1) animal.Name = (string)reader[i];
          }
          
          if (sector == sector.RT)
          {
              animal = (Cat)animal;
              //Convert animal to Cat and add two more field 
              //ISSUE: CatType and CatLoc are unknown at this point !
              if (i == 2) animal.CatType = (int)reader[i];
              if (i == 3) animal.CatLoc =  (int)reader[i];
          }
          
          yield return animal;
  }
  </code></pre>