Yield in c#
i've been trying to explain the keyword yield to a friend of mine for more than an hour and he did not get it.
but finally when i typed in this example he finally did
1: class enu :IEnumerable
2: { 3: public IEnumerator GetEnumerator()
4: { 5: yield return 1;
6: yield return 2;
7: yield return 3;
8: }
9: }
it actually means that when you are enumerating this object it will return a different value/object on every iteration
so the next time i revised this sample it was way easier to grasp the multiple returns
1: public class enu :IEnumerable
2: { 3: int _index=0;
4: int[] numbers = { 1, 2, 3, 4, 5 }; 5: public IEnumerator GetEnumerator()
6: { 7: yield return numbers[_index];
8: _index++;
9: }
10: }
now that i've gone this far i have to say that the enumerator here returns are not of a specific type nothing in the previous code specifies that the return type is an int
so..
after C# 2.0 has introduced generics this would work fine
1: public class enu :IEnumerable<int>
2: { 3: int _index=0;
4: int[] numbers = { 1, 2, 3, 4, 5 }; 5: public IEnumerator GetEnumerator()
6: { 7: yield return numbers[_index];
8: _index++;
9: }
10:
11: IEnumerator<int> IEnumerable<int>.GetEnumerator()
12: { 13: yield return numbers[_index];
14: _index++;
15: }
16: }
note that this new Interface IEnumerable<T> needs both methods to be implemented