Search code examples
c#asp.netrazoryield-return

Breakpoints not triggered in a method with yield-return


My function is like this

 IEnumerable<IPublishedContent> GetAllowedBlogs(IEnumerable<IPublishedContent> blogLandingNodes)
{
    foreach (var node in blogLandingNodes)
    {
        if ("Condition")
        {
            var blogsToDisplay = GetPostsForBlog(node);

            foreach (var blog in blogsToDisplay)
            {
                yield return blog;
            }
        }
        else
        {
            var blogsToDisplay = GetPostsForBlog(node, catId);

            foreach (var blog in blogsToDisplay)
            {
                yield return blog;
            }
        }
    }
}

When i put a break point and check I can see result nodes yielding, But when i check here

  IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node);

I get nothing, What is that I am doing wrong?


Solution

  • It's because all 'yielders' are converted to a lazy-enumeration.

    IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node);
    

    This line only creates the enumeration of Blogs, but does not execute it.
    Nothing really ran yet.

    Try this one and see if your breakpoint worked:

     IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node).ToList();
    

    (.ToList is from System.Linq namespace of course)

    FYI: this is not the point of the question, but you may find it interesting to see what yield really compiles into. The code and explanation under this link may be a little old, but main points will still apply: http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx