Monday 20 February 2017

Yield

The yield keyword before a return statement greatly simplifies creating a Numerator to enable the use of the for each loop. For a collection to be traversed by a foreeach loop that collection must implement the IEnumerable Interface which has one function that returns an instance of INumerator, now from my previous post we saw that it's a bit involved however the Yield keyword greatly simplifies that.

Let's start with a person class.

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthdate { get; set; }
    public int Age
    {
        get
        {
            var today = DateTime.Today;
            var age = today.Year - Birthdate.Year;
            return Birthdate > today.AddYears(-age) ? --age : age;
        }
    }

    public IEnumerable<DayOfWeek> BirthWeekDays() {
        for (int i = 0; i < this.Age+2; i++)
            yield return Birthdate.AddYears(i).DayOfWeek;
    }

    public override string ToString() { return $"{Age} {FirstName} {LastName}"; }

}

now this "Person" class differs slightly in the sense that it has the BirthWeekDays function, this function returns an IEnumerable of the DayOfWeek type; in essence it just returns every day of the week since you where born, so if you where born on a Tuesday, that's where it would start.

so let's see how it goes.

class Program
{
    static void Main(string[] args)
    {
        var p = new Person {
            FirstName = "Pawel",
            LastName = "Ciucias",
            Birthdate = new DateTime(1984, 1, 31)
        };

        foreach(var wd in p.BirthWeekDays())
            Console.WriteLine(wd.ToString());

        Console.WriteLine(p.ToString());
    }

}

now our application just zips through and lists all of the birth weekdays our person had since birth until their next birthday.