Implementing foreach-else for .Net (C#)
I like the idea of having else
-branches for loops as Python supports them for its for
and while
statements. It allows code like this:
else
is executed after the loop, unless the loop is terminated by a break
statement. Pretty handy, I think. I’ve decided this is awesome enough to justify the following extension method:
It’s your regular every day foreach
on IEnumerable
but allows you to specify both a “loop-action” and an “else-action” where the latter is executed after the loop unless you break the loop by returning false
from the former. It’s a tad clumsier than Python but still useful:
What do you think? Implementing WhileElse
is left as an exercise to the reader :)