Question

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?

Was it helpful?

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.

OTHER TIPS

A method that uses yield return will return an IEnumerable and possibly something more specific like an IEnumerable<int>. If you are only interested in the first item, you can call:

int myInt = myYieldReturnMethod().First();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top