Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a predicate as a function argument

Tags:

c#

.net

predicate

I want to be able to write something as

void Start(some condition that might evaluate to either true or false) {
    //function will only really start if the predicate evaluates to true
}

I'd guess it must be something of the form:

void Start(Predicate predicate) {
}

How can I check inside my Start function whenever the predicate evaluated to true or false? Is my use of a predicate correct?

Thanks

like image 212
devoured elysium Avatar asked Apr 24 '10 03:04

devoured elysium


3 Answers

Here's a trivial example of using a predicate in a function.

static void CheckRandomValueAgainstCriteria(Predicate<int> predicate, int maxValue)
{
    Random random = new Random();
    int value = random.Next(0, maxValue);

    Console.WriteLine(value);

    if (predicate(value))
    {
        Console.WriteLine("The random value met your criteria.");
    }
    else
    {
        Console.WriteLine("The random value did not meet your criteria.");
    }
}

...

CheckRandomValueAgainstCriteria(i => i < 20, 40);
like image 145
Anthony Pegram Avatar answered Nov 20 '22 15:11

Anthony Pegram


You could do something like this:

void Start(Predicate<int> predicate, int value)
    {
        if (predicate(value))
        {
            //do Something
        }         
    }

Where you call the method like this:

Start(x => x == 5, 5);

I don't know how useful that will be. Predicates are really handy for things like filtering lists:

List<int> l = new List<int>() { 1, 5, 10, 20 };
var l2 = l.FindAll(x => x > 5);
like image 2
Matt Dearing Avatar answered Nov 20 '22 16:11

Matt Dearing


From a design perspective, the purpose of a predicate being passed into a function is usually to filter some IEnumerable, the predicate being tested against each element to determine whether the item is a member of the filtered set.

You're better off simply having a function with a boolean return type in your example.

like image 1
Pierreten Avatar answered Nov 20 '22 17:11

Pierreten