Search code examples
c#yield-return

Can I call a yield return method outside of a loop?


There are situations in which a method should be used with yield return, but not in others.

The question is that if a method with yield return is used to assign values ​​to a variable only one item is returned.

In this situation two methods will be needed, one for regular use and the other with yield return.

Is there some way to use the method with yield return outside a loop?


Solution

  • Do you mean can you use yield return outside of a loop?

    The answer is yes:

    IEnumerable<string> GetStrings()
    {
        yield return "foo";
        yield return "bar";
        yield return "baz";
    }
    

    ...but this would be an unusual use case of yield return.