Note that there are some explanatory texts on larger screens.

plurals
  1. PODisposing an IDisposable in Linq
    primarykey
    data
    text
    <p><em>(This is a follow on from a comment on an answer to <a href="https://stackoverflow.com/questions/1751153/how-do-you-dispose-of-idisposableobject-create-inside-of-a-linq-expression">this</a> question)</em></p> <p>18 months after I posted it, someone spotted a bug in <a href="https://stackoverflow.com/questions/21280/am-i-missing-something-about-linq/80709#80709">one of my Linq examples</a>, where I use an IDisposable half way through a method chain, which never gets disposed.</p> <p>I attempted to write an extension method to handle this:</p> <pre><code>public static IEnumerable&lt;R&gt; Using&lt;T, R&gt;( this IEnumerable&lt;T&gt; list, Func&lt;T, R&gt; selector) where R : IDisposable { foreach(var item in list) using(var disposable = selector(item)) yield return disposable; } var q = Enumerable.Range(0, 10) .Using(i =&gt; new Disposable(i)) .Select(d =&gt; d.Id); </code></pre> <p>After seeing <a href="https://stackoverflow.com/questions/1751153/how-do-you-dispose-of-idisposableobject-create-inside-of-a-linq-expression/1751277#1751277">Marc's answer</a> to the question I referenced above, I wondered if I could overload the Select extension method directly, but if I do (by renaming <code>Using</code> to <code>Select</code>), the compiler squeals about <code>Select(d =&gt; d.Id)</code>, because <code>There is no implicit conversion from 'string' to 'System.IDisposable'</code>.</p> <p>Here's a test class...</p> <pre><code>public class Disposable : IDisposable { private string _id; private bool _disposed = false; public Disposable(int id) { Id = id.ToString(); Console.WriteLine("Creating " + Id); } public void Dispose() { Console.WriteLine("Disposing " + Id); _disposed = true; } public string Id { get { if(_disposed) throw new Exception("Call to disposed object!"); return _id; } set { _id = value; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload