Skip to content

Instantly share code, notes, and snippets.

@abeham
Last active August 25, 2016 15:39
Show Gist options
  • Save abeham/01e873d49e856e651993c56366331772 to your computer and use it in GitHub Desktop.
Save abeham/01e873d49e856e651993c56366331772 to your computer and use it in GitHub Desktop.
foreach-else
It would be nice in C# to have a foreach-else.
I would like the else branch to execute when the collection was empty.
In that sense, either I loop over a collection OR I execute this code.
This would change
var empty = true;
foreach (var e in enumeration) {
empty = false;
// ...
}
if (empty) {
// ...
}
to
foreach (var e in enumeration) {
// ...
} else {
// ...
}
Some people think that it's a solution to do
if (enumeration.Any()) {
foreach (var e in enumeration) {
// ...
}
} else {
// ...
}
But please note that
a) this requires allocations of unnecessary iterators
b) foreach is nested one additional level, but most important
c) you get those annoying warnings that you're enumerating your IEnumerable more than once.
I think the way it is named in Python is wrong. I don't have a name, but as it is explained
right in the beginning of an article [0] it is confusing and does not match the intuitively
expected behavior. What more reason do I need to discard this right away?
[0]: http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment