Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a bool condition to method which I can invoke when I need

Tags:

c#

I need to pass in a predicate which I can invoke whenever I want (just like a delegate). I am trying to do something like this (I thought Predicate delegate would meet my needs):

MyMethod(Predicate,string> pred);

Called like: MyMethod(s => s.Length > 5);

I want to write the condition inline BUT invoke it when I want, just like a delegate. How could I do this>?

Thanks

like image 496
GurdeepS Avatar asked Mar 15 '10 15:03

GurdeepS


2 Answers

You would do it exactly like you wrote:

void MyMethod(Func<string, bool> method)  // Could be Predicate<string> instead
{
    // Do something
    // ...
    // Later, if you choose to invoke your method:

    if( method(theString) )
    {
      //...
    }
}
like image 161
Reed Copsey Avatar answered Sep 28 '22 05:09

Reed Copsey


Like the following

bool MyMethod(Predicate<string> pred) {
  ...
  if ( pred("foo") ) { ... 
  }
}

Then

MyMethod(s => s.Length > 5);
like image 30
JaredPar Avatar answered Sep 28 '22 06:09

JaredPar