title: C# Generic loop to return list w/ type
body: <p>I noticed I had some duplicated code. How do I make this work in a more generic way?</p>
  
  <p>The class structure is </p>
  
  <pre><code>class BaseObject
  class MyBlock1 : BaseObject
  class MyBlock2 : BaseObject
  class MyBlock3 : BaseObject
  </code></pre>
  
  <p>The loop is:</p>
  
  <pre><code>private List&lt;MyBlock1&gt; GetVideosSection(IEnumerable&lt;ContentAreaItem&gt; items)
      {
          List&lt;MyBlock1&gt; blocks = null;
          if (items != null)
          {
              blocks = new List&lt;MyBlock1&gt;();
              foreach (var reference in items)
              {
                  var block = _repo.Get&lt;MyBlock1&gt;(reference.ContentLink);
                  blocks.Add(block);
              }
          }
          return blocks;
      }
  </code></pre>
  
  <p>The loop is repeated for each implementation of <code>BaseObject</code>.</p>
  
  <p>The <code>items</code> paremeter is a 'list' of references 'IDs' that are used to look up and return the appropriate object.</p>
  
  <p>My attempt was along the lines of</p>
  
  <pre><code>private List&lt;T&gt; GetBlocks&lt;T&gt;(IEnumerable&lt;ContentAreaItem&gt; items) where T : BlockData, new ()
      {
          List&lt;BaseObject&gt; blocks = null;
          if (items != null)
          {
              T typeDeclaredInMethod = T from GetBlocks&lt;T&gt;;
              blocks = new List&lt;  typeDeclaredInMethod &gt;();
              foreach (var reference in items)
              {
                  var block = _repo.Get&lt; typeDeclaredInMethod &gt;(reference.ContentLink);
                  blocks.Add(block);
              }
          }
          return blocks;
      }
  </code></pre>
  
  <p>I realize the above code is not valid but is there to illustrate my intent.
  I am new to C# and not sure how generic methods work so not sure if this is even possible.
  How can I write this loop to work for all implementations of <code>BaseObject</code>?</p>
  
  <p>Example of what I'm looking for:</p>
  
  <pre><code>List&lt;MyBlock1&gt; block1List = GetBlocks&lt;MyBlock1&gt;( items );
  List&lt;MyBlock2&gt; block2List = GetBlocks&lt;MyBlock2&gt;( items );
  List&lt;MyBlock3&gt; block3List = GetBlocks&lt;MyBlock3&gt;( items );
  </code></pre>
  
  <p>or </p>
  
  <pre><code>List&lt;BaseObject&gt; block1List = GetBlocks&lt;MyBlock1&gt;( items );
  </code></pre>