The yieldkeyword in C# is used to create iterators. An iterator is a method that can be used to iterate over a collection of data. The
yield keyword allows you to create iterators that can be used to iterate over collections that are not fully loaded into memory.
For example, the following code shows how to create an iterator that can be used to iterate over a list of numbers:
C#
public IEnumerable<int> GetNumbers()
{
int i = 0;
while (true)
{
yield return i;
i++;
}
}
This code creates a method called GetNumbers() that returns an iterator. The
GetNumbers() method uses the yield keyword to return the next number in the list. The
yield keyword also allows the GetNumbers() method to continue iterating even if the list of numbers is not fully loaded into memory.
The yield keyword can be used to create iterators for a variety of different collections, including lists, arrays, and sets. The
yield keyword can also be used to create iterators for custom collections.
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.
The
yieldkeyword in C# is used to create iterators. An iterator is a method that can be used to iterate over a collection of data. Theyieldkeyword allows you to create iterators that can be used to iterate over collections that are not fully loaded into memory.For example, the following code shows how to create an iterator that can be used to iterate over a list of numbers:
C#
This code creates a method called
GetNumbers()that returns an iterator. TheGetNumbers()method uses theyieldkeyword to return the next number in the list. Theyieldkeyword also allows theGetNumbers()method to continue iterating even if the list of numbers is not fully loaded into memory.The
yieldkeyword can be used to create iterators for a variety of different collections, including lists, arrays, and sets. Theyieldkeyword can also be used to create iterators for custom collections.