How to convert Func to Predicate?


Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);

Basically you can create a new delegate instance with any compatible existing instance. This also supports variance (co- and contra-):

Action<object> actOnObject = x => Console.WriteLine(x);
Action<string> actOnString = new Action<string>(actOnObject);

Func<string> returnsString = () => "hi";
Func<object> returnsObject = new Func<object>(returnsString);

If you want to make it generic:

static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
    return new Predicate<T>(func);

Leave a Comment