0

When would you use a Predicate Delegate over an Action Delegate?

For example, why does List<string>.RemoveAll() require a Predicate<string> rather than an Action<string>? I assume it is because Action<string> can only return a void. So is the only difference between them the return type of the delegate?

Sorry if this is too vague, I am trying to wrap my head around the nuances and the terms.

Harry Stuart
  • 1,781
  • 2
  • 24
  • 39
  • You can read about difference [here](https://stackoverflow.com/q/4317479/1997232). And if you still ask "when" question, then answer going to be opinion based. My opinion - never, use `Func<..., bool>` (obviously for void only option is `Action<...>`). – Sinatr Mar 08 '19 at 09:12

3 Answers3

1

They are entirely different - Action represents a void function; Predicate is an older version of Func<T, bool> - a generic function that accepts an object and returns a boolean value. Use depends on need, but it should never be a choice between these two types.

CoolBots
  • 4,770
  • 2
  • 16
  • 30
1

Predicate delegate as the name says constitutes a Predicate which would match a condition/predicate and return bool. Where as Action delegate as the signature says doesn't return anything (one way work).

List<string>.RemoveAll() requires a predicate cause, what if you want to remove all element T from list which matches a specific condition?

Rahul
  • 76,197
  • 13
  • 71
  • 125
-1

It is beautifully described here.

https://stackoverflow.com/a/55058355/11100119

  • While "configuring things" is _a use case_, `Action` delegates can be used for many purposes. Important aspect is that they represent `void` functions – CoolBots Mar 08 '19 at 06:24
  • @CoolBots yup, i gave an example, ofcourse there are so many implementations – AnonymousCodes Mar 08 '19 at 06:31