Saturday, November 7, 2009

Steps until failure

This is a piece of code i came accross that i thought that was interesting. I came accross this piece of code and i thought i should remember it for future reference

on Found on the website:
http://odetocode.com/Blogs/scott/default.aspx

void Process(){

Func<bool>[] steps = {
Step1,
Step2,
Step3,
Step4,
Step5
};

ExecuteStepsUntilFirstFailure(steps);

}

void ExecuteStepsUntilFirstFailure(IEnumerable<Func<bool>> steps)
{
steps.All(step => step() == true);
}

The All operator is documented as stopping as soon as a result can be determined, so the above code is equivalent to the following:

void ExecuteStepsUntilFirstFailure(IEnumerable<Func<bool>> steps)
{
foreach (var step in steps)
{
if (step() == false)
{
break;
}
}
}


No comments:

Post a Comment