.net – What does yield break; do in C#?

.net – What does yield break; do in C#?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

n

For example, if you define a function as an iterator, the body of the function may look like this:

n

for (int i = 0; i < 5; i++)n{n    yield return i;n}nnConsole.Out.WriteLine(You will see me);n

n

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

n

Or like this with yield break:

n

int i = 0;nwhile (true)n{n    if (i < 5)n    {n        yield return i;n    }n    elsen    {n        // note that i++ will not be executed after thisn        yield break;n    }n    i++;n}nnConsole.Out.WriteLine(Wont see me);n

n

In this case the last statement is never executed because we left the function early.

Ends an iterator block (e.g. says there are no more elements in the IEnumerable).

.net – What does yield break; do in C#?

Tells the iterator that its reached the end.

n

As an example:

n

public interface INoden{n    IEnumerable<Node> GetChildren();n}nnpublic class NodeWithTenChildren : INoden{n    private Node[] m_children = new Node[10];nn    public IEnumerable<Node> GetChildren()n    {n        for( int n = 0; n < 10; ++n )n        {n            yield return m_children[ n ];n        }n    }n}nnpublic class NodeWithNoChildren : INoden{n    public IEnumerable<Node> GetChildren()n    {n        yield break;n    }n}n

Leave a Reply

Your email address will not be published.