The yield
keyword in C# is used to create iterator methods or iterator blocks. An iterator method is a method that returns a sequence of values one at a time, instead of returning a single value. The yield
keyword allows you to easily implement iterator methods without having to write complex code to manage state and iteration.
Here's an example of an iterator method that uses the yield
keyword:
csharppublic IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
yield return 3;
yield return 4;
yield return 5;
}
In this example, the GetNumbers()
method is an iterator method that returns a sequence of integers. The yield
keyword is used to return each integer one at a time. When the yield
keyword is encountered, the value is returned, and the state of the method is saved. The next time the method is called, it resumes execution where it left off and continues until the next yield
keyword is encountered.
You can use the foreach
statement to iterate over the sequence of values returned by the iterator method:
csharpforeach (int num in GetNumbers())
{
Console.WriteLine(num);
}
In this example, the foreach
statement is used to iterate over the sequence of integers returned by the GetNumbers()
method. Each integer is printed to the console.
Iterator methods can be very useful when you need to work with large collections of data or when you need to perform complex operations on data that is too large to fit in memory. By using the yield
keyword, you can create efficient and easy-to-use iterator methods that can handle large data sets without consuming large amounts of memory.
Comments
Post a Comment