I'm unable to understand why Program.Fetch1
and Program.Fetch2
do not result in the exact same execution order. The only difference is that Program.Fetch1
is calling Program.Fetch
to do the actual fetch operation.
class Program
{
static IEnumerable<int> Fetch1()
{
using (Context c = new Context())
{
return Fetch(c);
}
}
static IEnumerable<int> Fetch(Context c)
{
foreach (int i in c.Fetch())
{
yield return i;
}
}
static IEnumerable<int> Fetch2()
{
using (Context c = new Context())
{
foreach (int i in c.Fetch())
{
yield return i;
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Fetch1:");
foreach (int i in Fetch1())
{
Console.WriteLine(i);
}
Console.WriteLine("Fetch2:");
foreach (int i in Fetch2())
{
Console.WriteLine(i);
}
}
}
class Context : IDisposable
{
public void Dispose()
{
Console.WriteLine("Context.Dispose");
}
public IEnumerable<int> Fetch()
{
return new int[] { 1, 2 };
}
}
Output:
Fetch1:
Context.Dispose
1
2
Fetch2:
1
2
Context.Dispose
My only guess is that Context.Dispose
is called first in Program.Fetch1
because the scope of the using declaration was already left. But this is true for Program.Fetch1
as well. So why do those method behave differently?
Update: My question is a duplicate of yield return statement inside a using() { } block Disposes before executing