title: Linq to Xml: Is XDocument a caching reader?
body: <p>I love the Linq to Xml API. Easiest one I've ever used. </p>
  
  <p>I also remembered it's implemented atop <code>XmlReader</code>, which is a non-caching reader, meaning: </p>
  
  <pre><code>var rdr = XmlReader.Create("path/to/huge_3Gb.xml");
  </code></pre>
  
  <p>...would return immediately (having probably read, at most, the xml header).</p>
  
  <p>The <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load.aspx" rel="nofollow">documentation</a> for <code>XDocument.Load()</code> states that indeed, it is using <code>XmlReader.Create()</code>. </p>
  
  <p>I expected, like with everything <em>Linq</em>, that I'd get deferred execution behaviour with Linq2Xml.<br>
  But then I tried this, like I usually do for anything that touches files: </p>
  
  <pre><code>using(var xdoc = XDocument.Load("file")){ ... }
  </code></pre>
  
  <p>and surprise! It does not compile, 'cause XDocument does NOT implement <code>IDisposable</code>!</p>
  
  <p>Hmm, that's peculiar! How will I <em>ever</em> release the file handle when I'm done using the <code>XDocument</code>?  </p>
  
  <p>And then it dawned on me: maybe <code>XDocument.Load()</code> eats up the whole Xml in memory, at once (and immediately closes the file handle)?</p>
  
  <p>So I tried :</p>
  
  <pre><code>var xdoc = XDocument.Load("path/to/huge_3Gb.xml");
  </code></pre>
  
  <p>and waited, and waited, and then the process said:</p>
  
  <pre><code>Unhandled Exception: OutOfMemoryException.
  </code></pre>
  
  <p>So Linq to Xml is close to perfection (awesome API), but no cigar (when used on large Xmls).</p>
  
  <p><code>&lt;/rant&gt;</code></p>
  
  <p><strong>My questions are:</strong></p>
  
  <ol>
  <li><p>Am I missing something and there IS a way to use Linq to Xml lazily?</p></li>
  <li><p>If the answer to the previous question is 'No':</p></li>
  </ol>
  
  <p>Is there an objective reason why the Linq to Xml API can't have deferred behaviour similar to, say, Linq to Objects? It looks to me that at least some operations (e.g. things that are possible with the forward-only <code>XmlReader</code>) could be implemented lazily.</p>
  
  <p>...Or is it not implemented like this, quoting <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx" rel="nofollow">Eric Lippert</a>,</p>
  
  <blockquote>
    <p>" because no one ever designed, specified, implemented, tested,
    documented and shipped that feature" ?</p>
  </blockquote>