How often did you use the Yield keyword??
1 min read
1 min read
yield
keyword? To be honest I
continuously forget to use it myself, too. But it would be so useful in certain scenarious. Take for instance:public IEnumerale<Person> FindMalePeople(IEnumerable<Person> people)
{
IEnumerable<Person> result = new IList<Person>();
foreach(Person person in people)
{
if(person.IsMale())
result.add(person);
}
return result;
}
yield
you could rewrite the above as follows: public IEnumerable<Person> FindMalePeople(IEnumerable<Person> people)Although initially you may get a little used to it in terms of readability, this code is much more memory efficient as we don't need to store the result in an intermediate temporary list as it was done in the 1st example.
{
foreach(Person person in people)
{
if(person.IsMale())
yield return person;
}
}