Alex Rivera | Logout

Some help understanding "yield"

Asked 2008-11-25T14:12:52.907
35

In my everlasting quest to suck less I'm trying to understand the "yield" statement, but I keep encountering the same error.

The body of [someMethod] cannot be an iterator block because 'System.Collections.Generic.List< AClass>' is not an iterator interface type.

This is the code where I got stuck:

foreach (XElement header in headersXml.Root.Elements()){
    yield return (ParseHeader(header));                
}

What am I doing wrong? Can't I use yield in an iterator? Then what's the point? In this example it said that List<ProductMixHeader> is not an iterator interface type. ProductMixHeader is a custom class, but I imagine List is an iterator interface type, no?

--Edit--
Thanks for all the quick answers.
I know this question isn't all that new and the same resources keep popping up.
It turned out I was thinking I could return List<AClass> as a return type, but since List<T> isn't lazy, it cannot. Changing my return type to IEnumerable<T> solved the problem :D

A somewhat related question (not worth opening a new thread): is it worth giving IEnumerable<T> as a return type if I'm sure that 99% of the cases I'm going to go .ToList() anyway? What will the performance implications be?

Edit
Report

1 Answer

3

List implements Ienumerable.

Here's an example that might shed some light on what you are trying to learn. I wrote this about 6 months

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YieldReturnTest
{
    public class PrimeFinder
    {
        private Boolean isPrime(int integer)
        {
            if (0 == integer)
                return false;

            if (3 > integer)
                return true;

            for (int i = 2; i < integer; i++)
            {
                if (0 == integer % i)
                    return false;
            }
            return true;
        }

        public IEnumerable<int> FindPrimes()
        {
            int i;

            for (i = 1; i < 2147483647; i++)
            {
                if (isPrime(i))
                {
                    yield return i;
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            PrimeFinder primes = new PrimeFinder();

            foreach (int i in primes.FindPrimes())
            {
                Console.WriteLine(i);
                Console.ReadLine();
            }

            Console.ReadLine();
            Console.ReadLine();
        }
    }
}
answered 2008-11-25T14:21:03.857

Your Answer