For Else
I was writing some code in a template that looked a lot like:
if (collection.HasItems)
{
foreach (var item in collection)
{
<some markup>
}
}
else
{
<some message about no items>
}
and I realized that it would be awfully nice for for
, foreach
, and while
loops to have an else
clause.
The above could be rewritten as:
foreach (var item in collection)
{
<some markup>
}
else
{
<some message about no items>
}
…which is a nice way to flatten arrow code as well as avoid redundancy. In my head it makes sense that the else
clause would only execute if the loop never executed.
I don't know if this exists somewhere already, or if there are significant drawbacks to this concept, but I'm certain I'd have use for this structure in a few different programming languages.
🗪 View Comments