Search code examples
c#-2.0yield-return

Method not called when using yield return


I'm having a little trouble with a method in which I use yield return this doesn't work...

public IEnumerable<MyClass> SomeMethod(int aParam)
{
    foreach(DataRow row in GetClassesFromDB(aParam).Rows)
    {
        yield return new MyClass((int)row["Id"], (string)row["SomeString"]);
    }    
}

The above code never runs, when the call is made to this method it just steps over it.

However if I change to...

public IEnumerable<MyClass> SomeMethod(int aParam)
{
    IList<MyClass> classes = new List<MyClass>();

    foreach(DataRow row in GetClassesFromDB(aParam).Rows)
    {
         classes.Add(new MyClass((int)rows["Id"], (string)row["SomeString"]);
    }

    return classes;
}

It works just fine.

I don't understand why the first method never runs, could you help me in understanding what is happening here?


Solution

  • The "yield" version is only "run" when the caller actually starts to enumerate the returned collection.

    If, for instance, you only get the collection:

    var results = SomeObject.SomeMethod (5);
    

    and don't do anything with it, the SomeMethod will not execute.

    Only when you start enumerating the results collection, it will hit.

    foreach (MyClass c in results)
    {
        /* Now it strikes */
    }