Reputation: 684
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;
Upvotes: 8
Views: 4734
Reputation: 236288
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.
Upvotes: 9
Reputation: 23732
Is there a way to use c# Predicate type for that? If not why?
Looking at the signature of Predicate<T>
is shows that it requires an argument or parameter:
public delegate bool Predicate<in T>(T obj)
So the quick answer here would be no. Because you have no parameters in your anonymous function.
But if you play a little around you can give the predicate some irrelevant object which it will not use anyway, like an alibi parameter:
Func<bool> predicate = () => 1 == 1;
Predicate<object> predicate2 = (x) => 1 == 1;
and the call would look like this:
Console.WriteLine(predicate());
Console.WriteLine(predicate2(null));
And this compiles and returns the correct result
Upvotes: 2