Search code examples
c#.netlinqdeferred-execution

Will Dispose be called first and cause a failure in case of deferred execution?


There are two methods, one of which returns a data using LINQ within a using statement. I wonder if it's possible for the query to throw some sort of an exception because the query execution is deferred and a variable it's using has already been disposed?

class Foo
{
    void Bar()
    {
       var bazResult = Baz();
       //... use bazResult here...
    }

    IEnumerable<int> Baz()
    {
        using (var d = new SomeDisposableSource())
        {
            return d.Select(e => e.Id);
        }
    }

}

BTW, it must have been asked already in some form but I can't find the obvious candidate. So don't kick me too hard :)


Solution

  • I think you will have an exception if the object is disposed. This thread is very similar and gives a couple of methods for handling the problem. The simple one is to force execution by doing a return d.Select(e => e.Id).ToList() but that might not be suitable for you