Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 693
Dolev Avatar asked Mar 14 '17 09:03

Dolev


People also ask

What is C in simple words?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

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.

like image 102
Sergey Berezovskiy Avatar answered Oct 19 '22 07:10

Sergey Berezovskiy


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

like image 22
Mong Zhu Avatar answered Oct 19 '22 06:10

Mong Zhu