Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops.

How often did you use the Yield keyword??

1 min read

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.
comments powered by Disqus