How can yield return statement return no elements?
Asked Answered
N

3

5

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.

Niche answered 3/11, 2012 at 20:20 Comment(1)
Is there any reason why you have to use yield?Bollix
H
15

Use the yield break statement:

private static IEnumerable<INode> YieldEmpty()
{
    yield break;
}
Heart answered 3/11, 2012 at 20:31 Comment(1)
Thank you! I used to believe the the yield break statement would stop the whole iterator, but now I understand it better.Niche
P
3

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

Poetry answered 3/11, 2012 at 20:29 Comment(2)
The correct syntax is Enumerable<T>.Empty()... An interface can not have a static methodDangerous
Thanks also, but I'm not in my machine. LinkPad is great!Bootjack
K
2
private static IEnumerable<T> ReturnNoElements()
{
   return Enumerable.Empty<T>();
}
Karajan answered 3/11, 2012 at 20:30 Comment(1)
Since IEnumerable<T> is a interface, it cannot be newedBernstein

© 2022 - 2024 — McMap. All rights reserved.