2

When should we use Action<T> and not to define a delegate explicitly?

Thanks

nawfal
  • 62,042
  • 48
  • 302
  • 339
amit kohan
  • 1,519
  • 2
  • 19
  • 42
  • Dupe: [creating-delegates-manually-vs-using-action-func-delegates](http://stackoverflow.com/questions/4482613/creating-delegates-manually-vs-using-action-func-delegates) – nawfal Jul 07 '14 at 16:48

2 Answers2

2

Well...

Action<T> is almost the same as delegate void (T t)
and
Func<T> is almost the same as delegate T ()

Action and Func (and lambdas) are just 'syntactical sugar' and a convenience for using delegates.

So it's really just a matter of preference.

Randy Minder
  • 43,558
  • 44
  • 173
  • 312
2

It's entirely a matter of preference, but I see no reason to ever define your own delegate if one of the overloads of Action or Func will work. If you have a ref/out/params parameter, optional arguments, or some other such edge cases you have no choice but to define your own.

Servy
  • 193,745
  • 23
  • 295
  • 406
  • Something else: Since .NET 4.0, `Action` is **contravariant** in `T`. But at the same time, delegate combination ("addition" of two delegate objects) doesn't work with contravariance (Lippert's words: [all messed up](http://stackoverflow.com/a/2307942/1336654)). So suppose you make a `public event Action ItHappened;`. Then because of contravariance, one subscriber could add an `Action` to `ItHappened`, another one an `Action`, a third one `Action`. That throws at runtime! So a reason to use a user-defined type is to **not** have contravariance. – Jeppe Stig Nielsen Nov 12 '12 at 12:00
  • While with Action/Func life is much easier, custom delegates give you better type safety (correctness). In the end there's a trade-off. Another benefit is the better (more meaningful) parameter name and IDE's documentation support. – nawfal Jul 07 '14 at 16:53