Skip to content

The yield keyword

The yield keyword can be used to return the value from a loop iteration, but without the need to have a List in between. For example, if you have a method like this:

public List<int> getNumbers()
{
    List<int> numbers = new List<int>();

    foreach (int number in pseudoClass.generateRandomNumber())
    {
        numbers.Add(number);
    }

    return numbers;
}

You could rewrite it like this:

public List<int> getNumbers()
{
    foreach (int number in pseudoClass.generateRandomNumber())
    {
        yield return number;
    }
}

(source)

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.