Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield can't understand the functionality

First, of all, I already search about this but i still can't I understand when to use yield.

For example I have the below code:

string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

public System.Collections.IEnumerator GetEnumerator()
{
    for (int i = 0; i < days.Length; i++)
    {
        yield return days[i];
    }
}

What would be the difference between the above code and below code?

string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

public System.Collections.IEnumerator GetEnumerator()
{
    for (int i = 0; i < days.Length; i++)
    {
        return days[i];
    }
}

Can you please tell me when to use yield?

like image 266
Pinoy2015 Avatar asked Jun 10 '26 06:06

Pinoy2015


1 Answers

The return method doesn't remember where you are in your array. It will return Sunday every single time you use it, simply because it starts that loop from zero every time.

Using yield is more (at least conceptually) "I'll return this value but, next time you call me, I'm going to pick up where I left off (inside the loop)".

A similar thing can be done in C with the use of static variables to remember where you are:

char *nextDay () {
    static char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
    static int nextDay = -1;
    nextDay = (nextDay + 1) % (sizeof (days) / sizeof (*days));
    return days[nextDay];
}

The fact that the nextDay variable is maintained across invocations of the function means that it can be used to cycle through the array.

like image 197
paxdiablo Avatar answered Jun 11 '26 18:06

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!