Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can yield return statement return no elements?

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.

like image 660
Josell Avatar asked Dec 04 '22 01:12

Josell


2 Answers

Use the yield break statement:

private static IEnumerable<INode> YieldEmpty()
{
    yield break;
}
like image 86
m0sa Avatar answered Dec 19 '22 20:12

m0sa


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...

like image 44
Raúl Otaño Avatar answered Dec 19 '22 20:12

Raúl Otaño