I know return returns use lazy loading, but I wonder if I can use the iterator incorrectly or maybe refactoring is needed.
My recursive iterator method returns all the ancestors of the given PageNode
, including the PageNode
itself.
public class PageNodeIterator { //properties and constructor left out for brevity public IEnumerable<IPageNode> ancestorsOf(IPageNode pageNode) { if(pageNode == null) throw new ArgumentNullException(("pageNode")); if (pageNode.url != pageNodeService.rootUrl) { yield return pageNode; if (pageNode.parent != null) foreach (var node in ancestorsOf(pageNode.parent)) yield return node; } } }
In my ancestorsOf
call, I call the method and then change the order of the returned IEnumerable
, but since loading is delayed, the call does not actually happen until I call ToArray()
on the next line and at this point the pageNodeService
is set to null in my iterator method and throw an exception zero reference.
ancestors = pageNodeIterator.ancestorsOf(currentNode).Reverse(); return ancestors.ToArray()[1].parent.children;
So, I wonder where I made a mistake. What would be the right way to use an iterator in this case, if at all?
I am also wondering why pageNodeService
is null at runtime. Even execution is delayed, shouldn't it still hold value?
source share