-
yield and Dispose()
Consider this code:
Code:
class Test : IDisposable
{
public void Dispose()
{
Console.WriteLine("dispose");
}
}
static IEnumerable<int> Bla()
{
using (new Test())
{
}
yield return 1;
yield return 2;
yield return 3;
}
I would expect after the using statement that dispose of Test is called when calling Bla(). But it isn't
Dispose is only called when calling Bla in a loop.
Code:
foreach (int i in Bla()) {break;}
Why?
-
That's because before you actually materialize your enumerable, Blah() isn't even called. Put a writeline before the new and you will see.
Code:
IEnumerable<int> GetAllData()
{
yield 1;
yield 2;
yield 3;
}
var data = GetAllData(); // <- function is NOT called. You got an IEnumerable. Not the actual data, but rather a hint where to get data, should it really be enumerated.
var materialized_data = data.ToList(); // <- now it gets called, the list will materialize the data
-