wasAsked.

what is yield keyword?

Mphasis · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

`yield return` defines an iterator. The compiler generates a state machine that produces one value each time the consumer advances the enumerator. This enables lazy streaming without building the entire result collection. `yield break` ends iteration. ```csharp public static IEnumerable<int> Fibonacci(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); int current = 0; int next = 1; for (int index = 0; index < count; index++) { yield return current; (current, next) = (next, checked(current + next)); } } foreach (int value in Fibonacci(7)) Console.WriteLine(value); // 0, 1, 1, 2, 3, 5, 8 ``` The method body starts when enumeration begins, not when `Fibonacci` is called. Each enumeration runs it again. Resource cleanup in a `using` or `finally` still occurs when the enumerator is disposed, so consumers should dispose enumerators—`foreach` does this automatically. For asynchronous streams, use `async IAsyncEnumerable<T>` with `yield return` and consume using `await foreach`.

Prince Yadav · · 0 likes

Sign in to add your answer

Related interview topics