Essential C# Yield Keyword  Suggest an edit

Try...finally

If an iterator method has a yield inside a try...finally, then the returned IEnumerator will execute the finally statement when Dispose is called on it, as long as the current point of evaluation is inside the try block.

Given the function:

private IEnumerable<int> Numbers()
{
    yield return 1;
    try
    {
        yield return 2;
        yield return 3;
    }
    finally
    {
        Console.WriteLine("Finally executed");
    }
}

When calling:

private void DisposeOutsideTry()
{
    var enumerator = Numbers().GetEnumerator();

    enumerator.MoveNext();
    Console.WriteLine(enumerator.Current);
    enumerator.Dispose();
}

Then it prints:

1

View Demo

When calling:

private void DisposeInsideTry()
{
    var enumerator = Numbers().GetEnumerator();

    enumerator.MoveNext();
    Console.WriteLine(enumerator.Current);
    enumerator.MoveNext();
    Console.WriteLine(enumerator.Current);
    enumerator.Dispose();
}

Then it prints:

1 2

Finally executed

View Demo


Table Of Contents
22 Enum
25 GUID
107 Stream
108 Timers
118 Yield Keyword
  ↑ ↓ to navigate     ↵ to select     Esc to close