How often did you use the Yield keyword??

If you think about your coding...how often have you used C#'s 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;
}

You would write something like the cods above, right? Well ok..forget about Linq for a moment ;-) . Instead by using yield you could rewrite the above as follows:
public IEnumerable<Person> FindMalePeople(IEnumerable<Person> people)
{
foreach(Person person in people)
{
if(person.IsMale())
yield return person;
}
}
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.
Kindle

Comments

0

Your ad here?