I'm practicing deletion of nodes on a binary search tree, and I created a special type for null links (NullNode) using null pattern, so I can add some desirable behaviour to "null" types. Both Node type and Nullnode type share the same INode interface, which includes recursive methods.

The INode interface includes IEnumerable recursive methods por PreOrder, InOrder and PostOrder traversal, but I don't want NullNode to return any element (through yield return statements).

What can I do?

I know that I can use an impossible if-condition and then put there a yield return statement in the method, but I don't think this solution is good. There should be a better approach.

有帮助吗?

解决方案

Use the yield break statement:

private static IEnumerable<INode> YieldEmpty()
{
    yield break;
}

其他提示

Had you tried returning something like this for no returning nothing (or an empty enumerator):

return Enumerable.Empty<T>();

Or maybe using yield break; can be an alternative for exit yields loops. Hope this could help you...

private static IEnumerable<T> ReturnNoElements()
{
   return Enumerable.Empty<T>();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top