Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top