T
Tony Johansson
Hello!
I have noticed that I can use iterator in a method and return an IEnumerable
like this
public IEnumerable<T> Reverse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data;
}
I can test this Reverse by having this code
foreach (string word in bc.Reverse())
Console.WriteLine(word);
Now to my question If I instead have defined the Reverse method like this
public IEnumerator<T> Reverse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data;
}
having IEnumerator as the return type I get compile
error saying "foreach statement cannot operate on variables of type
'System.Collections.Generic.IEnumerator<string>' because
'System.Collections.Generic.IEnumerator<string>' does not contain a public
definition for 'GetEnumerator'"
So I wonder how is the connection between a returning type for IEnumerable
and IEnumerator for a method using iterator and the statement call that is
used after the in keword in a foreach loop construction.
//Tony
I have noticed that I can use iterator in a method and return an IEnumerable
like this
public IEnumerable<T> Reverse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data;
}
I can test this Reverse by having this code
foreach (string word in bc.Reverse())
Console.WriteLine(word);
Now to my question If I instead have defined the Reverse method like this
public IEnumerator<T> Reverse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data;
}
having IEnumerator as the return type I get compile
error saying "foreach statement cannot operate on variables of type
'System.Collections.Generic.IEnumerator<string>' because
'System.Collections.Generic.IEnumerator<string>' does not contain a public
definition for 'GetEnumerator'"
So I wonder how is the connection between a returning type for IEnumerable
and IEnumerator for a method using iterator and the statement call that is
used after the in keword in a foreach loop construction.
//Tony