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.

1
  • Is there any reason why you have to use yield? Commented Nov 6, 2012 at 18:38

3 Answers 3

15

Use the yield break statement:

private static IEnumerable<INode> YieldEmpty() { yield break; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I used to believe the the yield break statement would stop the whole iterator, but now I understand it better.
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...

2 Comments

The correct syntax is Enumerable<T>.Empty()... An interface can not have a static method
Thanks also, but I'm not in my machine. LinkPad is great!
2
private static IEnumerable<T> ReturnNoElements() { return Enumerable.Empty<T>(); } 

1 Comment

Since IEnumerable<T> is a interface, it cannot be newed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.