c# Predicate with no parameters
Asked Answered
A

2

8

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;
Achieve answered 14/3, 2017 at 9:26 Comment(7)
Why do you want to do that? Func<bool> is the correct type.Infract
Predicate delegate requires one argument. You provide 0 arguments. So just use Func<bool> - that's perfectly fine. Of course if you like the name - you can define your own predicate: public delegate bool Predicate();Spode
Can you please explain what's wrong with Func<bool>? It's not clear what problem you are trying to solve.Impeccant
Predicate is just a synonym for Func<T,bool>Epistyle
I see it more readable using Predicate when it's a predicate. No logic behind it.Achieve
You might declare your own predicate as shown in my above comment (I've edited it so you might have missed it).Spode
Going against existing naming conventions isn’t really a good idea.Infract
I
9

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.

Impeccant answered 14/3, 2017 at 10:14 Comment(0)
J
2

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

Julietjulieta answered 14/3, 2017 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.