I suggest you ...

if finally & loop finally clauses

A clause which is run after any of the conditions in an if tree are true. Note: When used with else, the finally clause will only run if any of the other conditions are true. Sort of like an else-else.

And a final clause which is run if the loops exits from its own condition, not breaking. Instead of reduntantly checking the i variable. Should work for both foreach and for loops.

Syntax:
if (something)
doOne();
else if (something)
doTwo();
finally
ifOneOrTwo();

foreach (var item in collection)
// run loop
finally
// do something

Before:

var done = true;
if (something)
{

}
else if (somethingelse)
{

}
else
done = false;

if (done)
{
// do something
}
After:

if (something)
{

}
else if (somethingelse)
{

}
finally
{
// do something

Before:

for (int i = 0; i < 10; i++)
{
// run loop
if (i + 1 == 10)
// do something
}
After:

for (int i = 0; i < 10; i++)
// run loop
finally
// do something

For better example view and all my suggestions visit http://www.jsmars.com/csharp.php

3 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Jonathan Smårs shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    1 comment

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...
      • Philippe commented  ·   ·  Flag as inappropriate

        In my opinion, this add little benefit while making the code harder to understand as you have to know more language construct.

        And although, your sample code might works nice the first time, at some point while maintaining the code, you might realize that you don't want to always execute the code inside finally block or that you want to execute it even if the preceding code was not executed.

        So I do thing that using the "done" flag is still the best solution although that in some case it might make sense to move the code inside a function and simply return a boolean indicating if the condition was verified.

      Feedback and Knowledge Base