What is the use of the yield keyword in C#?
What is the use of the yield keyword in C#?
122
12-Jul-2023
Updated on 13-Jul-2023
Aryan Kumar
13-Jul-2023The
yield
keyword in C# is used to create iterators. An iterator is a method that can be used to iterate over a collection of data. Theyield
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#
This code creates a method called
GetNumbers()
that returns an iterator. TheGetNumbers()
method uses theyield
keyword to return the next number in the list. Theyield
keyword also allows theGetNumbers()
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. Theyield
keyword can also be used to create iterators for custom collections.