Offer a combined yield return and yield break syntax #815
Replies: 5 comments 1 reply
-
I'm thinking that the need to yield a single result and immediately break the iterator is a pretty uncommon pattern that doesn't necessitate a special syntax. You're either iterating a value deferred in which case the current syntax is perfectly sufficient, or you're bailing early prior to any deferred calculation in which |
Beta Was this translation helpful? Give feedback.
-
Can't this be solved with local functions? private static IEnumerable<int> GetValues(bool someCondition, bool someOtherCondition)
{
IEnumerable<int> GetValuesLocal()
{
foreach (var value in Enumerable.Range(0, 10))
yield return value;
}
if (someCondition)
return new[] { 1 };
var valuesLocal = GetValuesLocal();
if (someOtherCondition)
return valuesLocal.Concat(new[] { 2 });
return valuesLocal;
} Although I appreciate you may not want to add the local function structure verbosity, but it will reduce the And unfortunately the Concat forces you to have an extra allocation. |
Beta Was this translation helpful? Give feedback.
-
you could invert if to move the yield at the end of method so break is not necessary. in other words, ensure that yield return is the last statement in every code path. |
Beta Was this translation helpful? Give feedback.
-
Another idea for the syntax:
This variant is nearly self-descriptive for anyone who understands the current keywords. Either way, having such a statement would be nice, at the very least just to remove a superfluous line of code. I'd rather do this than contort a function with if-block-nesting just to get the yield returns at the end. |
Beta Was this translation helpful? Give feedback.
-
Not a huge fan of this but if accepted, the syntax should be: yield break x; To yield x as the final element of a sequence. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I've found myself doing the following more than a few times
and often wishing that there was a simplified version, perhaps
I understand the first thing one may think "well, simply place the yield before the check." That does work for simple enumerations, but I've found myself creating more complex enumerations that act as producers and use return values as a way to communicate to consumers. You might want to yield a work item when processing, but you might want to end after yielding an EOF, or a validation error, or a value indicating cancellation was requested.
The pattern could also be simplified by simply throwing an exception, but these results aren't necessarily exceptional situations, and communicating normal, expected outputs via exceptions is a tad hacky.
Beta Was this translation helpful? Give feedback.
All reactions