Home Dashboard Directory Help
Search

"else" clause on "foreach" for no-element collections by TimwiTerby


Status: 

Closed
 as External Help for as External


5
0
Sign in
to vote
Type: Suggestion
ID: 489186
Opened: 9/10/2009 12:39:09 PM
Access Restriction: Public
0
Workaround(s)
view

Description

For the next version of the C# language, I would like to suggest a new, simple language construct.

I often find myself writing code to the effect of:

if (someCollection.Count() == 0) {
// code to handle an empty collection
} else {
foreach (var item in someCollection) {
    // code to handle items in the collection
}
}

Aside from being repetitive typing, this construct has a significant flaw: for lazy-evaluation collections, this evaluates the collection twice, which may be significant. In performance-relevant cases, I thus end up writing the much more verbose

using (var enumerator = someCollection.GetEnumerator()) {
bool haveElement = enumerator.MoveNext();
if (!haveElement) {
    // code to handle empty collection
} else {
    do {
     var item = enumerator.Current;
     // code to handle each item
     haveElement = enumerator.MoveNext();
    } while (haveElement);
}
}

My suggested new language construct (see "Suggestion", below) is syntactic sugar for that.
Details
Sign in to post a comment.
Posted by Microsoft on 6/14/2010 at 6:18 PM
Thanks for the great suggestion for Visual Studio!

I've added a vote for a foreach-else clause to the OneNote notebook we use internally to track C# compiler and language requests. We can't promise if or when we'll get to this feature, but we'll definitely keep it in mind during planning for the next release!

For now, the following workaround should have the same performance as the second code snippet you mentioned, as .Any() stops iterating after finding a single element (or a lack of elements):

if (!someCollection.Any()) {
// code to handle an empty collection
} else {
foreach (var item in someCollection) {
    // code to handle items in the collection
}
}

Alex Turner
Program Manager
Visual Basic and C# Compiler
Posted by Microsoft on 9/11/2009 at 2:19 AM
Thank you for your feedback, we are currently reviewing the feedback you have submitted.
Sign in to post a workaround.