17
May
08

yielding

While reviewing xUnit’s sourcecode, I’ve stumbled upon this:

static IEnumerable<string> SplitLines(string input)
{
while (true)
{
int idx = input.IndexOf(Environment.NewLine);

if (idx < 0)
{
yield return input;
break;
}

yield return input.Substring(0, idx);
input = input.Substring(idx + Environment.NewLine.Length);
}
}

Thats a very nice use of yield. I’ve translated it to python just for fun:

Python

>>> def split(str):
while True:
idx = str.find(‘\n’);
if(idx < 0):
yield str
break

yield str[0:idx]
str = str[idx+1 :]

>>> g = split(“hello\nworld\nyea”)
>>> g.next()
‘hello’
>>> g.next()
‘world’
>>> g.next()
‘yea’


0 Responses to “yielding”



  1. No Comments Yet

Leave a Reply