Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An example for using predicate to replace 'if' in c#?

Tags:

c#

predicate

I read that the 'if' keyword is evil, and better to use predicate to replace if. Then I googled, but still dont get it.

Can anyone be kind to provide an example?

like image 934
Benny Avatar asked Sep 11 '26 10:09

Benny


1 Answers

No matter what they say, if is not evil. There may be specific cases for which a Predicate is a better choice than an if (or a set of ifs).

For example,

 foreach (Foo f in fooList) {
     if (f.Equals(fooTarget)) {
        return f;
     }
 }

versus (.NET 2.0)

 fooList.Find(delegate (Foo f) { return f.Equals(fooTarget); });

or (later)

 fooList.Find(f => f.Equals(fooTarget));
like image 187
Vinko Vrsalovic Avatar answered Sep 12 '26 23:09

Vinko Vrsalovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!