here yield is doing simple thing like if name is bob then it will return the name to its calling environment....what special about it.we can write the same thing in another way like
IList<string> FindBobs(IEnumerable<string> names)
{
var bobs = new List<string>();
foreach(var currName in names)
{
if(currName == "Bob")
bobs.Add(currName);
}
return bobs;
}
so please guide me what is the difference of two above approach....and what is the importance of yield. it would be better if some one make me understand the usage of yield with few easy sample code. thanks
mou_inn
Participant
778 Points
955 Posts
what is the actual use of yield keyword
Apr 15, 2012 07:55 PM|LINK
i have seen many time this keyword yield but do not understand it's use. what it does and when to use it. here is sample code for yield.
IEnumerable<string> FindBobs(IEnumerable<string> names)
{
foreach(var currName in names)
{
if(currName == "Bob")
yield return currName;
}
}
here yield is doing simple thing like if name is bob then it will return the name to its calling environment....what special about it.we can write the same thing in another way like
IList<string> FindBobs(IEnumerable<string> names)
{
var bobs = new List<string>();
foreach(var currName in names)
{
if(currName == "Bob")
bobs.Add(currName);
}
return bobs;
}
so please guide me what is the difference of two above approach....and what is the importance of yield. it would be better if some one make me understand the usage of yield with few easy sample code. thanks