Passing a bool condition to a method that I can call when I need

I need to pass a predicate that I can call whenever I want (just like a delegate). I'm trying to do something like this (I thought the Predicate delegate would meet my needs):

MyMethod(Predicate,string> pred); 

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

I want to write an inline condition, but call it whenever I want, just like a delegate. How can i do this??

thanks

+6
c #
source share
2 answers

You would do it exactly as 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) ) { //... } } 
+3
source share

As below

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

Then

 MyMethod(s => s.Length > 5); 
+2
source share

All Articles