I know that yield return takes advantage of lazy loading but I'm wondering if I might be misusing the iterator or quite possibly need a refactor.
My recursive iterator method returns all the ancestors of a 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 call to ancestorsOf
, I'm calling the method and then reversing the order of the returned IEnumerable
, but since loading is deferred the call doesn't actually happen until I call ToArray()
on the next line and at that point pageNodeService
in my iterator method is null and a null reference exception is thrown.
ancestors = pageNodeIterator.ancestorsOf(currentNode).Reverse();
return ancestors.ToArray()[1].parent.children;
So, I'm wondering where I've gone wrong. What would be the proper way to use an iterator in this case, if at all?
I'm also wondering why pageNodeService
is null at the time of execution. Even the execution is deferred shouldn't it still hold a value?