The yield keyword in C# is used to define iterator methods or get accessors of custom iterators. It provides a concise and efficient way to implement custom iteration logic for collections without the need to explicitly create a separate class that implements IEnumerable or IEnumerator.
Creating Iterators:
public static IEnumerable<int> GetEvenNumbers(int limit){
for (int i = 0; i <= limit; i++)
{
if (i % 2 == 0)
{
yield return i;
}
}
}public static void Main(string[] args){
foreach (int number in GetEvenNumbers(10))
{
Console.Write($"{number} "); // Output: 0 2 4 6 8 10
}
Console.WriteLine();
}
- GetEvenNumbers is an iterator method because it uses yield return.
- When the foreach loop starts, GetEvenNumbers begins execution.
- For each even number, yield return i; is executed, returning the number to the foreach loop.
- The state of the for loop is saved between iterations.
- Once the loop finishes, the iteration ends.
Creating Custom Iterators
yield can also be used within the get accessor of an indexer or a property that returns a collection type. This allows you to implement custom iteration logic directly within the property or indexer.
public class MyCollection
{
private string[] items = { "apple", "banana", "cherry" };public IEnumerable<string> Fruits
{
get
{
foreach (string item in items)
{
yield return item.ToUpper();
}
}
}
}public static void Main(string[] args)
{
MyCollection collection = new MyCollection();
foreach (string fruit in collection.Fruits)
{
Console.WriteLine(fruit);
// Output:
// APPLE
// BANANA
// CHERRY
}
}
the get accessor of the Fruits property uses yield return to iterate over the internal items array and return an uppercase version of each fruit.