How to implement for-else and foreach-else in C# similar to Python's for-else and while-else?

Viewed 19232

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");
4 Answers
Related