Click here to Skip to main content
15,892,674 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 
GeneralRe: Typo / Notes Pin
Andreas Gieriet19-Jun-12 20:46
professionalAndreas Gieriet19-Jun-12 20:46 
Oops! That was a late minute change without re-compiling the change... Frown | :( I did fix the code - change is pending.
Thanks for your hint!

What concerns the function signatures: Yes, it only defines the delegate that return a given type. You do not need to define all possible function signatures - you can always call a lambda expression that calls your specific function of any signature, as long as it returns the given generic type T. Reflection or expression trees are not needed for that. Delegates are sufficient as shown in the form of Func<T> (see the example where ..., ()=>Step2(1,1), ... is called).

If you had other signatures, then you must define arguments to be passed to these individual functions - which is a bit difficult. You better go by lambda expressions to handle that, I guess.

Cheers
Andi

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.