Hello!
I have noticed that I can use iterator in a method and return an IEnumerable
like this
public IEnumerable<TRe verse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data[i];
}
I can test this Reverse by having this code
foreach (string word in bc.Reverse())
Console.WriteLi ne(word);
Now to my question If I instead have defined the Reverse method like this
public IEnumerator<TRe verse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data[i];
}
having IEnumerator as the return type I get compile
error saying "foreach statement cannot operate on variables of type
'System.Collect ions.Generic.IE numerator<strin g>' because
'System.Collect ions.Generic.IE numerator<strin g>' 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<TRe verse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data[i];
}
I can test this Reverse by having this code
foreach (string word in bc.Reverse())
Console.WriteLi ne(word);
Now to my question If I instead have defined the Reverse method like this
public IEnumerator<TRe verse()
{
for (int i = data.Count -1 ; i >=0 ; i--)
yield return data[i];
}
having IEnumerator as the return type I get compile
error saying "foreach statement cannot operate on variables of type
'System.Collect ions.Generic.IE numerator<strin g>' because
'System.Collect ions.Generic.IE numerator<strin g>' 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