code4it-dev / blog-comments

https://www.code4it.dev/
1 stars 0 forks source link

csharptips/yield-return #22

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

C# Tip: use yield return to return one item at the time - Code4IT

Yield is a keyword that allows you to return an item at the time instead of creating a full list and returning it as a whole.

https://www.code4it.dev/csharptips/yield-return

jamescurran commented 2 years ago

Don't limit yourself to lists....

IEnumerable<int> Fib(int a =1, int b=1)
{
    while(true)
    {
        yield return a;
        a = a + b;
        yield return b;
        b = b + a;
    }
}

Fib().Take(10).Dump();
bellons91 commented 2 years ago

Nice idea! Have you used yield for any other stuff?