What is the use of the yield
keyword in C#?
I didn't understand it from the MSDN reference... can someone explain it to me please?
Answer
I'm going to try and give you an example
Here's the classical way of doing, which fill up a list object and then returns it:
private IEnumerable GetNumbers()
{
var list = new List();
for (var i = 0; i < 10; i++)
{
list.Add(i);
}
return list;
}
the yield keyword returns items one by one like this :
private IEnumerable GetNumbers()
{
for (var i = 0; i < 10; i++)
{
yield return i;
}
}
so imagine the code that calls the GetNumbers function as following:
foreach (int number in GetNumbers())
{
if (number == 5)
{
//do something special...
break;
}
}
without using yield you would have to generate the whole list from 0-10 which is then returned, then iterated over until you find the number 5.
Now thanks to the yield keyword, you will only generate numbers until you reach the one you're looking for and break out the loop.
I don't know if I was clear enough..
No comments:
Post a Comment