Click here to Skip to main content
15,886,518 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Call Functions Until One Meets Condition

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Jun 2012CPOL 9.8K   3   2
This is an alternative for "Call Functions Until One Meets Condition"

Introduction

This is an alternative tip to the original tip[^].

It basically wraps the original tip into one function. I prefer wrapping such functionality into a function that tells about the intent of the construct (even some purists will argue that function calls cost execution time...).

Here comes the code:

C#
public static void RunToFirstMatch<T>(Func<T, bool> sentry, params Func<T>[] functions)
{
    functions.Any(f => sentry(f()));
}

The code is called as follows (see the original functions[^]):

C#
RunToFirstMatch(v => (v >= 5), Step1, ()=>Step2(1,1), Step3, Step4, ()=>0+1);

As said, the content is the same, I simply added some wrapping.

History

  • V1.0, 2012-06-19: Initial version
  • V1.1, 2012-06-19: Fixed code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions

 
SuggestionTypo / Notes Pin
AspDotNetDev19-Jun-12 18:34
protectorAspDotNetDev19-Jun-12 18:34 
A few notes...

You have a variable "match" and a variable "sentry". I think they are supposed to be the same variable.

As you have written it, you can't pass parameters to the functions (supposing they all have the same signature). You'd have to create a new function for each signature, which defeats most of the purpose of having a function. The only way I can think of to put this into a single function would require reflection or expression tree manipulation.

That being said, if somebody did need to repeat this pattern a few times using the same function signature, your approach does have some merit.

GeneralRe: Typo / Notes Pin
Andreas Gieriet19-Jun-12 20:46
professionalAndreas Gieriet19-Jun-12 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.