title: C# 4.0 Implicitly Typed Dynamic Objects
body: <p><strong>Data File:</strong> (<em>Data.txt</em>) lines represent <code>width height</code></p>
  
  <pre><code>5
  6 9
  7 2
  4 4
  </code></pre>
  
  <p><strong>C# Code:</strong></p>
  
  <pre><code>var list = new List&lt;dynamic&gt;();
  using (var sr = new StreamReader("Data.txt", Encoding.UTF8))
  {
      list = sr.ReadToEnd().Split('\n').Select(r =&gt;
      {
          var split = r.Split(' ');
          var len = split.Length;
          return new {
              w = len &gt; 0 ? int.Parse(split[0].Trim()) : 0,
              h = len &gt; 1 ? int.Parse(split[1].Trim()) : 0 
          } as dynamic;
      }).ToList();
  }
  int Area = list.Sum(r =&gt; r.h * r.w);
  </code></pre>
  
  <p>The example works as is. I had to do a few undesired things to make it work.</p>
  
  <p>First I had to declare the list to avoid the using scope - since I do not have a typed dimension object I made the type dynamic (<code>var list = new List&lt;dynamic&gt;()</code>). </p>
  
  <p>The undesirable part is casting the anonymous object to a dynamic (<code>as dynamic</code>). Otherwise I get </p>
  
  <blockquote>
    <p>Cannot implicitly convert type
    <code>System.Collections.Generic.List&lt;AnonymousType#1&gt;</code>
    to
    <code>System.Collections.Generic.List&lt;dynamic&gt;</code></p>
  </blockquote>
  
  <p><strong>Why do I get this error? I know a dynamic can hold an anonymous type, so is this a problem with the <code>ToList()</code> extension and dynamics?</strong></p>
  
  <p>I need to be able to access the anonymous list items outside of the using statement, as in the last line that calculates area.</p>
  
  <hr>
  
  <p><strong>Solution:</strong>
  I went with dtb's answer. It avoided the use of a using statement and dynamics all together. Thank you all for the input!</p>
  
  <pre><code>var list = 
      (from line in File.ReadLines("Data.txt")
      let parts = line.Split(' ')
      let width = int.Parse(parts[0])
      let height = parts.Length &gt; 1 ? int.Parse(parts[1]) : 0
      select new { width, height }).ToList();
  </code></pre>