Withyieldkeyword, the control moves from the caller to source and from the source back to the caller .
yieldstatement can be used in two forms: yield return <expression>;
yield returnstatement returns each element at at time.
Yield return allows you to run custom iteration without temp collection.
using System; using System.Collections.Generic; namespace RandomNumberApp { class RandomNumber { static void Main(string[] args) { foreach (int i in PrintRandomNumbers(10)) { Console.WriteLine(i); } Console.ReadLine();
} static IEnumerable<int> PrintRandomNumbers(int counter) { Random rand = new Random(); for (int i = 0; i < counter; i++) { yield return rand.Next(); } } } }
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
With yield keyword, the control moves from the caller to source and from the source back to the caller .
yield statement can be used in two forms: yield return <expression>;
yield return statement returns each element at at time.
Yield return allows you to run custom iteration without temp collection.