I don’t use yields often, but one place where they can be handy is when you want to return a collection of objects Just-In-Time.

One way to do this would be with a list (rather clumsy).

        public static IEnumerable<GasDay> GetEnumerator(GasDay inclusiveStart, GasDay inclusiveEnd)
        {
            List<GasDay> gasDays = new List<GasDay>();
            for (GasDay gasDay = inclusiveStart; gasDay.IsBeforeOrSame(inclusiveEnd); gasDay = gasDay.NextGasDay())
            {
                gasDays.Add(gasDay);
            }
        }

A more elegant way would be o use a yield.

        public static IEnumerable<GasDay> GetEnumerator(GasDay inclusiveStart, GasDay inclusiveEnd)
        {
            for (GasDay gasDay = inclusiveStart; gasDay.IsBeforeOrSame(inclusiveEnd); gasDay = gasDay.NextGasDay())
            {
                yield return gasDay;
            }
        }
Advertisements