Search code examples
c#anonymous-functionfunc

c# Predicate with no parameters


I'm trying to pass a Predicate to a function but it has no input. I'm actually trying to delay the computation until the call is made.

Is there a way to use c# Predicate type for that? If not why.

I know a way to do this with Func

Func<bool> predicate = () => someConditionBool;

But I want to do this:

Predicate<> predicate = () => someConditionBool;

Solution

  • If it's just a readability problem, then you can create your own delegate which returns boolean and don't have any parameters:

    public delegate bool Predicate();
    

    And use it this way

    Predicate predicate = () => someConditionBool;
    

    NOTE: You should keep in mind that everyone is familiar with default Action and Func delegates which are used in .NET, but Predicate is your custom delegate and it will be less clear at first time for average programmer.