13

Python's for and while loops include an optional else clause which execute if the loop exits normally (i.e. without a break statement). For example, in Python you could code:

for x in range(3):
    print(x)
else
    print("The loop exited normally")

And the output will be:

0
1
2
The loop exited normally

How would you accomplish something similar in C# in order to code something like the following:

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(x);                  
}
else
    Console.WriteLine("The loop exited normally");
clay
  • 1,757
  • 2
  • 20
  • 23
LEMUEL ADANE
  • 8,336
  • 16
  • 58
  • 72
  • 6
    Unless you actually give full definitions of what these magical constructs do, the question aint real. – leppie Jul 01 '11 at 11:14
  • 5
    Sounds suspiciously [Pythonic](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)... – BoltClock Jul 01 '11 at 11:15
  • Give us the scenario you want to use these constructions, I bet you can always put a if - else around your for or foreach loop. – Peter Jul 01 '11 at 11:15
  • I doubt pseudo-code was what leppie had in mind about "full definitions"... – BoltClock Jul 01 '11 at 11:23

4 Answers4

22

The Python Construct for foreach-else is like this:

foreach( elem in collection )
{
    if( condition(elem) )
        break;
}
else
{
    doSomething();
} 

The else only executes if break is not called during the foreach loop

A C# equivalent might be:

bool found = false;
foreach( elem in collection )
{
    if( condition(elem) )
    {
        found = true;
        break;
    }
}
if( !found )
{
    doSomething();
}

Source: The Visual C# Developer Center

Jon Egerton
  • 40,401
  • 11
  • 97
  • 129
6

Sure:

  • Use one of the fancy suggestions by the other posters

  • Use a method that performs the loop, instead of break, you can return to avoid executing code below the loop

  • Use a boolean variable you can set before you break, and test that after the loop

  • Use goto instead of break

It's a weird pattern though if you ask me. "Foreach" is always started so the word "else" does not make sense there.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • 3
    Aaargh - Goto. Really? – Jon Egerton Jul 01 '11 at 13:08
  • @JonEgerton, while I wouldn't quite use a goto here, I wouldn't condemn it either. The python for-else construct is just a special case `goto`. If you roll-your own goto, then you still have the same control of flow and have therefore not spagetified your code. Touble is, that you might accidentally spagetify it in some later change. – Adrian Ratnapala Jun 16 '14 at 10:46
  • I almost like the suggestion of goto, except it allows other code to enter it. – ArtOfWarfare Mar 12 '17 at 20:26
4

If you're referring to the for-else and while-else constructs in Python, there is a basic IEnumerable<T> extension method that simulates a foreach-else described in this article, with the following implementation:

public static void ForEachElse<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> action, Action @else)
{
    foreach (var i in source)
    {
        if (!action(i))
        {
            return;
        }
    }
    @else();
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
4

Googling it gave me that : http://www-jo.se/f.pfleger/.net-for-else

public static void ForEachElse<TSource>(
this IEnumerable<TSource> source,
Func<TSource>,
bool action,
Action @else
)  // end of parameters
{
foreach (var i in source)
  {
    if (!action(i))
      {
        return;
      }
  }
   @else();
}
mehmetseckin
  • 3,061
  • 1
  • 31
  • 43